"""
    Action chech MA profiles
"""

import os
from pathlib import Path
import urllib
import lib
from lib.actions import Action
from lib.alpm import AlpmBranch


class ActionProfiles(Action):

    @staticmethod
    def usage():
        return "profiles : Check manjaro m-a iso profiles"

    def test(self):
        # not force one branch ...
        super().test()
        return True

    def list_desktops_url(self, desktop_filters):
        """
            return generator on all desktop
        """
        desks = "xfce", "kde", "gnome"
        for desk in desks:
            if desktop_filters and desk not in desktop_filters:
                continue
            yield "manjaro/" + desk
        desks = (
            "openbox-regular",
            "mate",
            "bspwm-mate",
            "openbox-minimal",
            "deepin",
            "bspwm",
            "cinnamon",
            "lxqt",
            "openbox-basic",
            "awesome",
            "budgie",
            "lxde",
            "i3",
            "webdad"
        )
        for desk in desks:
            if desktop_filters and desk not in desktop_filters:
                continue
            yield "community/" + desk

    def extract_pkg_from_profile(self, file_name: str):
        """
            parse desktop file for extract packages
        """
        result = []
        with open(file_name, 'rt') as f_pro:
            for line in f_pro:
                if '>i686' in line:
                    continue
                line = line.strip()
                if not line or line.startswith('#'):
                    continue
                result.append(line.split('#')[0].strip().split()[-1])
        return frozenset(sorted(result))

    def run(self):
        """
            check packages in iso profiles
        """
        super().run()
        # we can add profile desktop in parameter for test only some
        desktop_filters = self.params.values
        if desktop_filters:
            desktop_filters = set(x.lower() for x in desktop_filters)
            print("Download only:", desktop_filters)
        local_profil = self.params.option('profil', 'p') # not used, not load but use local directory

        # download MA profiles
        profiles = []
        for desk in self.list_desktops_url(desktop_filters):
            url = f"https://gitlab.manjaro.org/profiles-and-settings/iso-profiles/raw/manjaro-architect/{desk}/Packages-Desktop"
            print("url:", url)
            filename = f"{lib.TMP_DIR}/iso-profiles/{desk}/Packages-Desktop"
            os.makedirs(os.path.dirname(filename), exist_ok=True)
            try:
                urllib.request.urlretrieve(url, filename)
            except urllib.error.HTTPError:
                pass

        # find all profiles
        for f_packages in Path(f"{lib.TMP_DIR}/iso-profiles").glob('*/*/Packages-Desktop'):
            profiles.append(f_packages)

        def check_branch(branch_name: str):
            """ test for one branch """
            print("")
            branch = AlpmBranch(branch_name)
            pkgs = sorted([p.name for p in branch.pkg_search('')])
            self.msg(f"Branch: {branch.color(branch_name)}{branch_name}{branch.color('none')}")
            for profile in profiles:
                pkgs_profile = self.extract_pkg_from_profile(profile)
                # return packages are not in pkgs(packages in prepos)
                only_in = pkgs_profile - set(pkgs)
                print("\n->", profile.parent.name.upper())
                if only_in:
                    self.msg(f"{len(only_in)}:", *only_in)

        for branchname in AlpmBranch.BRANCHES:
            if branchname == 'archlinux':
                continue
            if self.params.branch and self.params.branch != branchname:
                continue
            check_branch(branchname)
