pyh0n/pyhon/parameter/base.py

88 lines
2.6 KiB
Python
Raw Normal View History

2023-05-21 05:55:43 +05:30
from typing import Dict, Any, List, Tuple, Callable, TYPE_CHECKING
if TYPE_CHECKING:
from pyhon.rules import HonRule
2023-04-16 05:13:37 +05:30
class HonParameter:
2023-05-06 19:37:28 +05:30
def __init__(self, key: str, attributes: Dict[str, Any], group: str) -> None:
2023-04-16 05:13:37 +05:30
self._key = key
self._category: str = attributes.get("category", "")
self._typology: str = attributes.get("typology", "")
self._mandatory: int = attributes.get("mandatory", 0)
self._value: str | float = ""
2023-05-06 19:37:28 +05:30
self._group: str = group
2023-06-28 22:32:11 +05:30
self._triggers: Dict[
str, List[Tuple[Callable[["HonRule"], None], "HonRule"]]
] = {}
2023-04-16 05:13:37 +05:30
@property
def key(self) -> str:
return self._key
@property
def value(self) -> str | float:
return self._value if self._value is not None else "0"
2023-05-28 09:47:43 +05:30
@value.setter
def value(self, value: str | float) -> None:
self._value = value
self.check_trigger(value)
2023-05-22 04:37:55 +05:30
@property
2023-06-09 05:39:20 +05:30
def intern_value(self) -> str:
return str(self.value)
2023-05-22 04:37:55 +05:30
2023-04-24 08:03:00 +05:30
@property
def values(self) -> List[str]:
2023-05-06 19:37:28 +05:30
return [str(self.value)]
2023-04-24 08:03:00 +05:30
2023-04-16 05:13:37 +05:30
@property
def category(self) -> str:
return self._category
@property
def typology(self) -> str:
return self._typology
@property
def mandatory(self) -> int:
return self._mandatory
2023-05-06 19:37:28 +05:30
@property
def group(self) -> str:
return self._group
2023-05-21 05:55:43 +05:30
2023-06-28 22:32:11 +05:30
def add_trigger(
self, value: str, func: Callable[["HonRule"], None], data: "HonRule"
) -> None:
2023-05-21 05:55:43 +05:30
if self._value == value:
func(data)
self._triggers.setdefault(value, []).append((func, data))
2023-06-28 22:32:11 +05:30
def check_trigger(self, value: str | float) -> None:
2023-05-21 05:55:43 +05:30
if str(value) in self._triggers:
for trigger in self._triggers[str(value)]:
func, args = trigger
func(args)
@property
2023-06-28 22:32:11 +05:30
def triggers(self) -> Dict[str, Any]:
result: Dict[str, Any] = {}
2023-05-21 05:55:43 +05:30
for value, rules in self._triggers.items():
2023-06-10 10:11:37 +05:30
for _, rule in rules:
if rule.extras:
param = result.setdefault(value, {})
for extra_key, extra_value in rule.extras.items():
param = param.setdefault(extra_key, {}).setdefault(
extra_value, {}
)
else:
param = result.setdefault(value, {})
if fixed_value := rule.param_data.get("fixedValue"):
param[rule.param_key] = fixed_value
else:
param[rule.param_key] = rule.param_data.get("defaultValue", "")
2023-05-21 05:55:43 +05:30
return result