"""
    Application Actions
"""
import sys
import os
import subprocess
import json
from lib.alpm import AlpmBranch

class Action():
    """ Général action """

    def __init__(self, params: object):
        """ class initialisation """
        self.params = params
        self.key = params.action
        self.error = ''

    @staticmethod
    def usage() -> str:
        """ return action help """
        return "Not implémented"

    def test(self) -> bool:
        """
        test parameters
        set self.error and/or create exception
        """
        if self.params.option("help", "h"):
            print(f"\n{self.usage().replace('           ', '')}\n")
            exit(0)
        return True

    def run(self):
        """ execute action """
        pass

    @property
    def color(self) -> str:
        """return color branch"""
        if self.params.branch:
            return AlpmBranch.color(self.params.branch)
        else:
            return AlpmBranch.color('none')

    def msg(self, *args):
        """format message with curent branch color"""
        print(f"{self.color}::{AlpmBranch.color('none')}", *args)


class ActionPlugin():
    path = "~/.config/mbn"
    def __init__(self, key: str = None):
        self.key = key
        self.params = {}
        self.usage()    # test if good plugin

    def test(self) -> bool:
        return True

    def usage(self):
        os.environ['PACMAN_ROOT'] = AlpmBranch.ROOT
        stdout, _ = subprocess.Popen(f"{self.path}/mbn-{self.key} get-plugin-metadata", shell=True, text=True, stdout=subprocess.PIPE).communicate()
        j = json.loads(stdout)
        return j["ShortDescription"]

    def run(self):
        os.environ['PACMAN_ROOT'] = AlpmBranch.ROOT
        if self.params.branch:
            os.environ['PACMAN_BRANCH'] = self.params.branch
        subprocess.run(f"{self.path}/mbn-{self.key} {' '.join(sys.argv)}", shell=True, text=True)

class SwitchClass():
    """ switch/case Class """

    def __init__(self, params: dict = None):
        """ class initialisation """
        self.classes = {}
        if params and isinstance(params, dict):
            self.classes = params

    def provide(self, key: str, class_type):
        """ add one action """
        if key:
            self.classes[key] = class_type
        return self

    def get(self, key: str, default=None):
        """ find class action """
        return self.classes.get(key, default)

    def factory(self, key: str, params: dict):
        """ create action object """
        action_type = self.get(key, self.get('usage'))
        if isinstance(action_type, ActionPlugin):
            action_type.params = params
            return action_type
        return action_type(params)
