83 lines
2.7 KiB
Python
83 lines
2.7 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
|
|
from typing import Self, Callable, Any, Optional
|
|
from Interfaces.Application.CXCVInterface import CXCVInterface
|
|
from Utils.Utils import Utils
|
|
|
|
class CommandsModel:
|
|
|
|
def __set_action(self:Self,
|
|
action:Callable[[dict[str, Any|None], list[Any|None]], None]|str|None
|
|
) -> None:
|
|
if callable(action):
|
|
self.__action = action
|
|
elif isinstance(action, str):
|
|
|
|
parts:list[str] = action.split(".")
|
|
item:Any|None = (
|
|
self.cxcv if parts[0] == "cxcv" else
|
|
None)
|
|
|
|
if item:
|
|
for part in parts[1:]:
|
|
if hasattr(item, part):
|
|
item = getattr(item, part)
|
|
else:
|
|
item = None
|
|
break
|
|
else:
|
|
item = eval(action)
|
|
|
|
if callable(item):
|
|
self.__action = item
|
|
|
|
def __init__(self:Self,
|
|
cxcv:CXCVInterface,
|
|
names:str|list[str]|tuple[str, ...],
|
|
action:Callable[[dict[str, Any|None], list[Any|None]], None]|str|None = None
|
|
) -> None:
|
|
self.cxcv:CXCVInterface = cxcv
|
|
self.__names:list[str] = Utils.get_keys(names)
|
|
self.__action:Callable[[dict[str, Any|None], list[Any|None]], None]|None = None
|
|
|
|
self.__set_action(action)
|
|
|
|
def get_names(self:Self) -> list[str]:
|
|
return [*self.__names]
|
|
|
|
def get_action(self:Self) -> Callable[[dict[str, Any|None], list[Any|None]], None]|None:
|
|
return self.__action
|
|
|
|
def check(self:Self, names:str|list[str]|tuple[str, ...]) -> bool:
|
|
return Utils.get_keys(names)[0] == self.__names[0]
|
|
|
|
def update(self:Self,
|
|
names:str|list[str]|tuple[str, ...]|Self|None = None,
|
|
action:Optional[Callable[[dict[str, Any|None], list[Any|None]], None]] = None
|
|
) -> bool:
|
|
|
|
if isinstance(names, CommandsModel):
|
|
action = names.get_action()
|
|
names = names.get_names()
|
|
|
|
names = Utils.get_keys(names)
|
|
|
|
if names[0] == self.__names[0]:
|
|
for name in names[1:]:
|
|
if name not in self.__names:
|
|
self.__names += [name,]
|
|
if action is not None and action != self.__action:
|
|
self.__set_action(action)
|
|
return True
|
|
return False
|
|
|
|
def execute(self:Self,
|
|
name:str,
|
|
parameters:dict[str, Any|None],
|
|
*arguments:list[Any|None]
|
|
) -> bool:
|
|
if name in self.__names and self.__action is not None:
|
|
self.__action(parameters, *arguments)
|
|
return True
|
|
return False |