"""
    parse console arguments
"""

import re
import lib
from lib.alpm import AlpmBranch
from lib.exceptions import BranchError

class ConsoleParser:
    """Arguments pass by console"""

    def __init__(self, args):
        self._args = args[1:]
        if self._args and self._args[0] == '-v':
            print(lib.DESCRIPTION, ":", lib.version_str())
            exit(0)
        self.expend()
        self.parse_branches()
        self.action = 'update'
        self.branch = ''
        self.branch_two = ''
        self.options = {}
        self.values = []
        try:
            self.action = self._args.pop(0).lower()
        except IndexError:
            self.action = ''

        self.read_branch()
        self.parse()
        #self.show()

    def show(self):
        """for debug"""
        print("args", self._args)
        print("action", self.action)
        print("branch", self.branch)
        print("branch 2", self.branch_two)
        print("options", self.options)
        print("params", self.values)
        #exit(0)

    def expend(self):
        """ split short option to options """
        # convert -suq -> -s -u -q
        regex = re.compile(r'^-[a-z]{2,}')
        for i, arg in enumerate(self._args):
            if not regex.search(arg):
                continue
            self._args[i] = arg[0:2]
            long_arg = arg[2:].strip()
            for c_arg in long_arg:
                self._args.insert(i+1, f"-{c_arg}")

    def parse_branches(self):
        """convert short branch"""
        # switch = {'-a':'--archlinux', '-u':'--unstable', '-t':'--testing', '-g':'--stable-staging', '-s':'--stable'}
        switch = {'-a': '--archlinux', '-u': '--unstable', '-t': '--testing', '-s': '--stable'}
        for i, arg in enumerate(self._args):
            self._args[i] = switch.get(arg, arg)
        for i, arg in enumerate(self._args):
            if arg.lower() in switch.values():
                self._args[i] = arg.lower()

    def read_branch(self):
        """find branch in console argument"""
        self.branch = None
        for arg in self._args:
            if arg[2:] in AlpmBranch.BRANCHES:
                if not self.branch:
                    self.branch = arg[2:]
                else:
                    if self.branch != arg[2:]:
                        self.branch_two = arg[2:]
        if self.branch:
            self._args.remove(f"--{self.branch}")
        if self.branch_two:
            self._args.remove(f"--{self.branch_two}")

    def get_branches(self) -> str:
        """find branches in console argument and order"""
        if not self.branch_two:
            raise BranchError(f"set second branch !")
        if AlpmBranch.BRANCHES.index(self.branch) < AlpmBranch.BRANCHES.index(self.branch_two):
            return (self.branch, self.branch_two)
        else:
            return (self.branch_two, self.branch)

    def parse(self) -> None:
        """set params in values et options with arg"""
        # get values
        for i, arg in enumerate(self._args):
            if arg.startswith('-'):
                break
            else:
                self.values.append(arg)
                self._args[i] = '.'
        # get options
        for i, arg in enumerate(self._args):
            if arg == '.':
                continue
            if arg.startswith('-'):
                # if "-d5"
                if arg[2:] and not arg[2:].isalpha():
                    arg_data = arg[2:]
                    arg = arg[0:2]
                else:
                    arg_data = (self._args[i+1:i+2] or (True,))[0]
                    # test next param if is a value or option
                    if not isinstance(arg_data, bool):
                        if arg_data.startswith('-'):
                            arg_data = True
                        else:
                            self._args[i+1] = '.'
                self._args[i] = '.'
                self.options[arg] = arg_data

    def option(self, key: str, short_key: str = ''):
        """return option"""
        result = self.options.get(f"--{key}", False)
        if not result:
            result = self.options.get(f"-{short_key}", False)
        return result
