from sqlalchemy import desc
from app.extensions.database import session
from app.extensions.utils.log_helper import logger_
from app.extensions.utils.time_helper import get_str_from_today, get_str_from_time
from app.persistence.model.plant_info_model import PlantInfoModel
from app.persistence.model.receive_failure_history_model import (
    ReceiveFailureHistoryModel,
)
from core.domains.iot.dto.iot_dto import CreateReceiveDataDto, FailureReceiveDataDto

logger = logger_.getLogger(__name__)


class IOTRepository:
    def create_receive_data(self, dto: CreateReceiveDataDto) -> None:
        try:
            model = PlantInfoModel(
                plant_id=dto.plant_id,
                sensormac=dto.sensormac,
                interrupt=dto.interrupt,
                temperature=dto.temperature,
                indoor_humidity=dto.indoor_humidity,
                soil_humidity=dto.soil_humidity,
                illuminance=dto.illuminance,
                created_date=get_str_from_today(),
                created_time=get_str_from_time(),
            )
            session.add(model)
            session.commit()
        except Exception as e:
            logger.error(
                f"[IOTRepository][create_receive_data] sensormac : {dto.sensormac} error : {e}"
            )
            session.rollback()
            raise e

    def create_failure_receive_data(self, dto: FailureReceiveDataDto) -> None:
        try:
            model = ReceiveFailureHistoryModel(
                sensormac=dto.sensormac,
                receive_data=dto.receive_data,
                reason=dto.reason,
                created_date=get_str_from_today(),
            )
            session.add(model)
            session.commit()
        except Exception as e:
            logger.error(
                f"[IOTRepository][create_failure_receive_data] sensormac : {dto.sensormac} error : {e}"
            )
            session.rollback()

    def get_predict_data(self, plant_id: int) -> list[PlantInfoModel]:
        query = (
            session.query(PlantInfoModel)
            .filter(PlantInfoModel.plant_id == plant_id)
            .order_by(
                desc(PlantInfoModel.created_date), desc(PlantInfoModel.created_time)
            )
            .limit(720)
        )
        queryset = session.execute(query).scalars().all()
        return queryset
