"""
        Action tree
"""
import os
import subprocess
import re
from lib.actions import Action
from lib.alpm import AlpmBranch


class ActionTree(Action):

    @staticmethod
    def usage():
        return "tree : local database tree informations"

    def run(self):
        """show local database tree structure"""
        super().run()

        subprocess.call(['tree', '--noreport', '-I', 'local|hooks|pacman.log', AlpmBranch.ROOT])
        regex_kernel = re.compile(r'^linux(\d+)(|-rt)$')
        regex_packager = re.compile(r'manjaro')
        for branchname in AlpmBranch.BRANCHES:
            nbs = {}
            packagers = {}
            linuxs = []
            branch = AlpmBranch(branchname)
            if branchname == 'archlinux':
                continue
                #regex_kernel = re.compile('^(linux|linux-lts)$')
            for db in branch.get_repos():
                pkgs = db.search('')
                nbs[db.name] = len(pkgs)
                if db.name in 'core': #['core', 'community'] add community for to have kernels-rt
                    linuxs = linuxs + [x.name for x in pkgs if regex_kernel.search(x.name)]
                packagers[db.name] = len([x.packager for x in pkgs if regex_packager.search(x.packager)])

            print(f"\n{branch.color(branchname)}:: {branchname:22}{branch.color('none')} {sum(nbs.values()):>6_} {sum(packagers.values()):>10_}".replace('_', ' '))
            for key in nbs:
                print(f"   {branch.color(branchname)}-{branch.color('none')} {key:20} {nbs[key]:>6_} {packagers[key]:>10_}".replace('_', ' '))
            if linuxs:
                print("  ", *reversed(linuxs), sep=" ")

        if not os.path.isfile(f"{AlpmBranch.ROOT}/unstable/etc/pacman.conf"):
            return
        regex_path = re.compile(r'^Server(.?)=(?P<path>[^#]+)')
        with open(f"{AlpmBranch.ROOT}/unstable/etc/pacman.conf", 'r') as conf:
            for line in conf:
                matchs = regex_path.match(line.lstrip())
                if not matchs:
                    continue
                path = matchs.group('path')
                if path:
                    print(f"\nServer: {AlpmBranch.color('i')}{path.strip()[0:-21]}{AlpmBranch.color('none')}")
                    return
