import os

import salt.cli.caller
import salt.defaults.exitcodes
import salt.utils.parsers
from salt.config import _expand_glob_path, prepend_root_dir


class SaltCall(salt.utils.parsers.SaltCallOptionParser):
    """
    Used to locally execute a salt command
    """

    def run(self):
        """
        Execute the salt call!
        """
        self.parse_args()

        if self.options.file_root:
            file_roots = []
            for file_root in self.options.file_root:
                # check if the argument is pointing to a file on disk
                file_roots.append(os.path.abspath(file_root))
            self.config["file_roots"] = {"base": _expand_glob_path(file_roots)}

        if self.options.pillar_root:
            pillar_roots = []
            for pillar_root in self.options.pillar_root:
                # check if the argument is pointing to a file on disk
                pillar_roots.append(os.path.abspath(pillar_root))
            self.config["pillar_roots"] = {"base": _expand_glob_path(pillar_roots)}

        if self.options.states_dir:
            states_dirs = []
            for states_dir in self.options.states_dir:
                # check if the argument is pointing to a file on disk
                states_dirs.append(os.path.abspath(states_dir))
            self.config["states_dirs"] = states_dirs

        if self.options.local:
            self.config["file_client"] = "local"
        if self.options.master:
            self.config["master"] = self.options.master

        if self.options.cachedir and self.config.get(
            "extension_modules"
        ) == os.path.join(self.config.get("__cachedir"), "extmods"):
            # Override `extension_modules`, but only in case if it was autogenerated
            cache_dir = os.path.abspath(self.options.cachedir)
            self.config["cachedir"] = cache_dir
            self.config["extension_modules"] = os.path.join(cache_dir, "extmods")
            prepend_root_dir(self.config, ["cachedir", "extension_modules"])

        caller = salt.cli.caller.Caller.factory(self.config)

        if self.options.doc:
            caller.print_docs()
            self.exit(salt.defaults.exitcodes.EX_OK)

        if self.options.grains_run:
            caller.print_grains()
            self.exit(salt.defaults.exitcodes.EX_OK)

        caller.run()
