from dataclasses import dataclass, field
from typing import Dict, Set

from ._PropertyModel import PropertyModel
from ._SchemaModel import SchemaModel
from ._SchemaPropertyTypeEnum import SchemaPropertyTypeEnum
from ..utils import set_dict_path_value


@dataclass
class ObjectSchemaModel(SchemaModel, PropertyModel):
    properties: Dict[str, PropertyModel] | None = None
    required: Set[str] = field(default_factory=set)

    def add_property(
        self,
        name: str,
        prop: PropertyModel,
        required: bool = True
    ) -> None:
        if self.properties is None:
            self.properties = {}

        set_dict_path_value(
            dict_value=self.properties,
            path=[name],
            value=prop
        )

        if required:
            self.required.add(name)
        elif name in self.required:
            self.required.remove(name)

    def to_dict(self) -> dict:
        return {
            "type": SchemaPropertyTypeEnum.object,
            "properties": self.properties,
            "required": list(self.required),
        }
