|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | +import os |
| 5 | +from dataclasses import dataclass |
| 6 | +from enum import Enum |
| 7 | +from pathlib import Path |
| 8 | +from typing import TYPE_CHECKING, cast |
| 9 | + |
| 10 | +import yaml |
| 11 | +from qgis.core import QgsProject |
| 12 | +from qgis.utils import iface |
| 13 | + |
| 14 | +from arho_feature_template.qgis_plugin_tools.tools.resources import resources_path |
| 15 | + |
| 16 | +if TYPE_CHECKING: |
| 17 | + from typing import Literal |
| 18 | + |
| 19 | + from qgis.core import QgsMapLayer |
| 20 | + from qgis.gui import QgisInterface |
| 21 | + |
| 22 | + iface: QgisInterface = cast("QgisInterface", iface) # type: ignore[no-redef] |
| 23 | + |
| 24 | + |
| 25 | +logger = logging.getLogger(__name__) |
| 26 | + |
| 27 | +DEFAULT_PLAN_REGULATIONS_CONFIG_PATH = Path(os.path.join(resources_path(), "kaavamaaraykset.yaml")) |
| 28 | + |
| 29 | + |
| 30 | +class ConfigSyntaxError(Exception): |
| 31 | + def __init__(self, message: str): |
| 32 | + super().__init__(f"Invalid config syntax: {message}") |
| 33 | + |
| 34 | + |
| 35 | +class UninitializedError(Exception): |
| 36 | + def __init__(self): |
| 37 | + super().__init__("PlanRegulationsSet is not initialized. Call 'load_config' first") |
| 38 | + |
| 39 | + |
| 40 | +class ValueType(Enum): |
| 41 | + POSITIVE_DECIMAL = "positiivinen desimaali" |
| 42 | + POSITIVE_INTEGER = "positiivinen kokonaisluku" |
| 43 | + POSITIVE_INTEGER_RANGE = "positiivinen kokonaisluku arvoväli" |
| 44 | + VERSIONED_TEXT = "kieliversioitu teksti" |
| 45 | + |
| 46 | + |
| 47 | +class Unit(Enum): |
| 48 | + SQUARE_METERS = "k-m2" |
| 49 | + CUBIC_METERS = "m3" |
| 50 | + EFFICIENCY_RATIO = "k-m2/m2" |
| 51 | + PERCENTAGE = "prosentti" |
| 52 | + AREA_RATIO = "m2/k-m2" |
| 53 | + |
| 54 | + |
| 55 | +# TODO: Same as in PlanManager, should refactor |
| 56 | +def get_layer_by_name(layer_name: str) -> QgsMapLayer | None: |
| 57 | + """Retrieve a layer by name from the project.""" |
| 58 | + layers = QgsProject.instance().mapLayersByName(layer_name) |
| 59 | + if layers: |
| 60 | + return layers[0] |
| 61 | + iface.messageBar().pushMessage("Error", f"Layer '{layer_name}' not found", level=3) |
| 62 | + return None |
| 63 | + |
| 64 | + |
| 65 | +def get_name_mapping_for_plan_regulations(layer_name: str) -> dict[str, dict[str, str]] | None: |
| 66 | + layer = get_layer_by_name(layer_name) |
| 67 | + if not layer: |
| 68 | + return None |
| 69 | + return {feature["value"]: feature["name"] for feature in layer.getFeatures()} |
| 70 | + |
| 71 | + |
| 72 | +@dataclass |
| 73 | +class PlanRegulationsSet: |
| 74 | + """Describes the set of plan regulations.""" |
| 75 | + |
| 76 | + version: str |
| 77 | + regulations: list[PlanRegulationConfig] |
| 78 | + |
| 79 | + _instance: PlanRegulationsSet | None = None |
| 80 | + |
| 81 | + @classmethod |
| 82 | + def get_instance(cls) -> PlanRegulationsSet: |
| 83 | + """Get the singleton instance, if initialized.""" |
| 84 | + if cls._instance is None: |
| 85 | + raise UninitializedError |
| 86 | + return cls._instance |
| 87 | + |
| 88 | + @classmethod |
| 89 | + def get_regulations(cls) -> list[PlanRegulationConfig]: |
| 90 | + """Get the list of regulation configs, if instance is initialized.""" |
| 91 | + instance = cls.get_instance() |
| 92 | + return instance.regulations |
| 93 | + |
| 94 | + @classmethod |
| 95 | + def initialize( |
| 96 | + cls, |
| 97 | + config_path: Path = DEFAULT_PLAN_REGULATIONS_CONFIG_PATH, |
| 98 | + type_of_plan_regulations_layer_name="Kaavamääräyslaji", |
| 99 | + language: Literal["fin", "eng", "swe"] = "fin", |
| 100 | + ) -> PlanRegulationsSet: |
| 101 | + # Initialize PlanRegulationsSet and PlanRegulationConfigs from config file |
| 102 | + with config_path.open(encoding="utf-8") as f: |
| 103 | + data = yaml.safe_load(f) |
| 104 | + cls._instance = cls.from_dict(data) |
| 105 | + |
| 106 | + # Add names from plan regulation layer |
| 107 | + mapping = get_name_mapping_for_plan_regulations(type_of_plan_regulations_layer_name) |
| 108 | + if mapping: |
| 109 | + for regulation in cls.get_regulations(): |
| 110 | + regulation.add_name(mapping, language) |
| 111 | + |
| 112 | + logger.info("PlanRegulationsSet initialized successfully.") |
| 113 | + return cls._instance |
| 114 | + |
| 115 | + @classmethod |
| 116 | + def from_dict(cls, data: dict) -> PlanRegulationsSet: |
| 117 | + file_version = data["version"] |
| 118 | + try: |
| 119 | + return cls( |
| 120 | + version=file_version, |
| 121 | + regulations=[PlanRegulationConfig.from_dict(config) for config in data["plan_regulations"]], |
| 122 | + ) |
| 123 | + except KeyError as e: |
| 124 | + raise ConfigSyntaxError(str(e)) from e |
| 125 | + |
| 126 | + |
| 127 | +@dataclass |
| 128 | +class PlanRegulationConfig: |
| 129 | + """Describes the configuration of a plan regulation.""" |
| 130 | + |
| 131 | + regulation_code: str |
| 132 | + name: str |
| 133 | + category_only: bool |
| 134 | + value_type: ValueType | None |
| 135 | + unit: Unit | None |
| 136 | + child_regulations: list[PlanRegulationConfig] |
| 137 | + |
| 138 | + @classmethod |
| 139 | + def from_dict(cls, data: dict) -> PlanRegulationConfig: |
| 140 | + """ |
| 141 | + Initialize PlanRegulationConfig from dict. |
| 142 | +
|
| 143 | + Intializes child regulations recursively. |
| 144 | + """ |
| 145 | + return cls( |
| 146 | + regulation_code=data["regulation_code"], |
| 147 | + name=data["regulation_code"], |
| 148 | + category_only=data.get("category_only", False), |
| 149 | + value_type=ValueType(data["value_type"]) if "value_type" in data else None, |
| 150 | + unit=Unit(data["unit"]) if "unit" in data else None, |
| 151 | + child_regulations=[PlanRegulationConfig.from_dict(config) for config in data.get("child_regulations", [])], |
| 152 | + ) |
| 153 | + |
| 154 | + def add_name(self, code_to_name_mapping: dict[str, dict[str, str]], language: Literal["fin", "eng", "swe"]): |
| 155 | + language_to_name_dict = code_to_name_mapping.get(self.regulation_code) |
| 156 | + self.name = language_to_name_dict[language] if language_to_name_dict else self.regulation_code |
| 157 | + for regulation in self.child_regulations: |
| 158 | + regulation.add_name(code_to_name_mapping, language) |
0 commit comments