"""
    Action pactree
"""

import subprocess
from lib.actions import Action
from lib.alpm import AlpmBranch


class ActionPactree(Action):

    @staticmethod
    def usage():
        return "pactree : as original command, only --sync"

    def test(self):
        super().test()
        if not self.params.values:
            raise ValueError(f"Nothing to find !")
        return True

    def run(self, pkg_name: str = ''):
        """ main """
        super().run()
        use_reverse = self.params.option('reverse', 'r')
        use_list = self.params.option('linear', 'l')
        use_depth = self.params.option('depth', 'd')
        if not pkg_name:
            pkg = self.params.values.pop(0)
        else:
            pkg = pkg_name
            use_list = True
        result = ''

        for branch_name in AlpmBranch.BRANCHES:
            if self.params.branch and branch_name != self.params.branch:
                continue
            args = ['pactree', pkg, '-s', '-b', f"{AlpmBranch.ROOT}/{branch_name}/lib/pacman"]
            if use_reverse:
                args.append('-r')
            if use_list:
                args.append('-l')
                args.append('-u')
            if use_depth and use_depth.isdigit():
                args.append(f"-d{use_depth}")
            if not pkg_name:
                self.msg(f"Branch: {AlpmBranch.color(branch_name)}{branch_name}{AlpmBranch.color('none')}")

            if pkg_name:
                #capture call output in result
                process, error = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
                if not error:
                    result += process.decode()
            else:
                subprocess.call(args)

        if pkg_name:
            return result.split()
