"""
    Action update
"""

from lib.actions import Action
from lib.action import actionrm
from lib.alpm import AlpmBranch
from lib.exceptions import BranchNotFoundError


class ActionUpdate(Action):

    @staticmethod
    def usage():
        return """
            update [--force or -f] [--files] [--mirrors | -m] : update all branches
            update --testing [--force or -f] [--files]: update one branch
            """

    def run(self, branch_name: str = ''):
        """ create or update databases """
        super().run()
        from_gui = self.params.option('gui')
        self.force = self.params.option('force', 'f')
        files = self.params.option('files')

        self.pacman_mirror()

        def update_branch(branch_name: str, from_gui: bool):
            branch = AlpmBranch(branch_name)
            if from_gui:
                print(f":: Branch: {branch_name}")
                branch.do_update(self.force)
            else:
                self.msg(f"Branch: {branch.color(branch_name)}{branch_name}{branch.color('none')}")
                branch.do_refresh(self.force, files)

        if branch_name:
            self.params.branch = branch_name
        try:
            if self.params.branch:
                update_branch(self.params.branch, from_gui)
            else:
                for br in AlpmBranch.BRANCHES:
                    update_branch(br, from_gui)
        except BranchNotFoundError:
            # structure not exists -> create folders and .conf
            for br in AlpmBranch.BRANCHES:
                AlpmBranch.create_branch(br)
                self.msg(f"Branch: {AlpmBranch.color(br)}{br}{AlpmBranch.color('none')}")
                if from_gui:
                    AlpmBranch(br).do_update(self.force)
                else:
                    AlpmBranch(br).do_refresh(True, files)
        else:
            raise

    def pacman_mirror(self):
        if not self.params.option('mirrors', 'm') or self.params.option('gui'):
            return

        import urllib, json

        with urllib.request.urlopen('https://repo.manjaro.org/status.json') as f_url:
            req = f_url.read()#.decode('utf-8')
        mirrors = json.loads(req)
        mirrors = [m for m in mirrors if m['branches'] == [1, 1, 1]]
        sorted(mirrors, key=lambda colonnes: colonnes['country'])
        i = 0
        for i, mirror in enumerate(mirrors):
            print(f"{i+1:2}", f"{mirror['country']:20} {mirror['last_sync']:7} {mirror['url']}")
        id_choice = -1
        i += 1

        while id_choice < 0:
            value = input(f"Enter a number (1..{i}) : ")
            if not value:
                break
            try:
                if int(value) <= i:
                    id_choice = int(value)
            except ValueError:
                pass

        if id_choice > 0:
            id_choice -= 1
            print(f"\n   {mirrors[id_choice]['country']:20} {mirrors[id_choice]['last_sync']:7} {mirrors[id_choice]['url']}")
            # update .conf
            self.force = AlpmBranch.set_server(mirrors[id_choice]['url'])
            actionrm.ActionRm(self.params).run()     # remove all cache

        if not self.params.option('files'):
            print("\n:: !! files not updated !!\n")
        #if force:
        #    files = True
