Coretex
list_enum_parameter.py
1 # Copyright (C) 2023 Coretex LLC
2 
3 # This file is part of Coretex.ai
4 
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 
18 from typing import Any, List, Optional, Tuple, Dict
19 
20 import logging
21 
22 from ..base_list_parameter import BaseListParameter
23 from ..utils import validateEnumStructure
24 from ....project import ProjectType
25 
26 
27 class ListEnumParameter(BaseListParameter[Dict[str, Any]]):
28 
29  @property
30  def types(self) -> List[type]:
31  return NotImplemented
32 
33  @property
34  def listTypes(self) -> List[type]:
35  return NotImplemented
36 
37  def validate(self) -> Tuple[bool, Optional[str]]:
38  isValid, message = validateEnumStructure(self.name, self.value, self.required)
39  if not isValid:
40  return isValid, message
41 
42  # validateEnumStructure already checks if value is of correct type
43  value: Dict[str, Any] = self.value # type: ignore[assignment]
44 
45  selected = value["selected"]
46  options = value["options"]
47 
48  if selected is None and not self.required:
49  return True, None
50 
51  if not isinstance(selected, list):
52  return False, f"Enum list parameter \"{self.name}.selected\" has invalid type. Expected \"list[int]\", got \"{type(selected).__name__}\""
53 
54  if not all(type(element) is int for element in selected):
55  elementTypes = ", ".join({type(element).__name__ for element in selected})
56  return False, f"Enum list parameter \"{self.name}.selected\" has invalid type. Expected \"list[int]\", got \"list[{elementTypes}]\""
57 
58  invalidIndxCount = len([element for element in selected if element >= len(options) or element < 0])
59  if invalidIndxCount > 0:
60  return False, f"Enum list parameter \"{self.name}.selected\" has out of range values"
61 
62  return True, None
63 
64  def parseValue(self, type_: ProjectType) -> Optional[Any]:
65  if self.value is None:
66  return self.value
67 
68  selected: Optional[List[int]] = self.value["selected"]
69  options: List[str] = self.value["options"]
70 
71  if selected is None:
72  return None
73 
74  return [options[value] for value in selected]
75 
76  def overrideValue(self, values: Optional[Any]) -> Optional[Any]:
77  if values is None or self.value is None:
78  return None
79 
80  try:
81  parsedValue: Dict[str, Any] = self.value
82  parsedValue["selected"] = []
83 
84  for value in values.split(" "):
85  parsedValue["selected"].append(int(value))
86 
87  return parsedValue
88  except ValueError as e:
89  logging.getLogger("coretexpylib").warning(f">> [Coretex] Failed to override list[enum] parameter \"{self.name}\". | {e}")
90  return self.value