from pydantic import (
    BaseModel,
    ValidationError,
    StrictStr,
    StrictFloat,
    validator,
    confloat,
)

from app.extensions.utils.log_helper import logger_
from core.domains.iot.dto.iot_dto import CreateReceiveDataDto
from core.exceptions import InvalidRequestException

logger = logger_.getLogger(__name__)


class CreateReceiveDataSchema(BaseModel):
    sensormac: StrictStr | None
    interrupt: StrictStr | None
    temperature: StrictFloat | None
    indoor_humidity: StrictFloat | None
    soil_humidity: StrictFloat | None
    illuminance: StrictFloat | None

    @validator("temperature", "indoor_humidity", "soil_humidity", "illuminance")
    def check_type(cls, check_field):
        if not isinstance(check_field, float):
            raise ValidationError(f"[CreateReceiveDataSchema][check_NaN] error")
        return check_field


class CreateReceiveDataRequestSchema:
    def __init__(
        self,
        sensormac: str | None,
        interrupt: str | None,
        temperature: str,
        humidity: str,
        soilhumidity: str,
        illuminance: str,
    ):
        self.sensormac = sensormac
        self.interrupt = interrupt
        self.temperature = temperature
        self.humidity = humidity
        self.soil_humidity = soilhumidity
        self.illuminance = illuminance

    def validate_request_and_make_dto(self):
        try:
            schema = CreateReceiveDataSchema(
                sensormac=self.sensormac,
                interrupt=self.interrupt,
                temperature=float(self.temperature),
                indoor_humidity=float(self.humidity),
                soil_humidity=float(self.soil_humidity),
                illuminance=float(self.illuminance),
            ).dict()
            return CreateReceiveDataDto(**schema)
        except ValidationError as e:
            logger.error(
                f"[CreateReceiveDataRequestSchema][validate_request_and_make_dto] error : {e}"
            )
            raise InvalidRequestException(message=e.errors())
