"""
        Action find package duplicate
"""

import collections
from lib.actions import Action
from .actionsearch import ActionSearch
from lib.alpm import AlpmBranch
from lib.exceptions import BranchError


class ActionDuplicate(Action):

    @staticmethod
    def usage():
        return "command : find package duplicates over repos"

    def test(self):
        super().test()
        if not self.params.branch:
            raise BranchError(f"Enter a valid branch {AlpmBranch.BRANCHES}")
        return True

    def run(self):
        """ find package duplicates over repos """
        super().run()
        self.params.options['--quiet'] = True   # for search
        for branchname in AlpmBranch.BRANCHES:
            if self.params.branch and self.params.branch != branchname:
                continue
            self.find_dupp(branchname)

    def find_dupp(self, branch_name: str):
        #self.params.branch = branch_name
        branch = AlpmBranch(branch_name)
        pkgs = sorted((p.name for p in branch.pkg_search('')))
        dupps = [p for p, count in collections.Counter(pkgs).items() if count > 1]
        search = ActionSearch(self.params)
        if dupps:
            print("")
            reg = ''
            for dupp in dupps:
                reg += f"^{dupp}$|"
            search.run(reg.rstrip('|'))
