# InitialConditionsAdisTSSpec.py -- Pamhyr
# Copyright (C) 2023-2025  INRAE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# -*- coding: utf-8 -*-

import logging

from tools import trace, timer

from Model.Tools.PamhyrDB import SQLSubModel
from Model.Except import NotImplementedMethodeError
from Model.Scenario import Scenario

logger = logging.getLogger()


class ICTemperatureSpec(SQLSubModel):
    _sub_classes = []

    def __init__(self, id: int = -1, name: str = "",
                 status=None, owner_scenario=None):
        super(ICTemperatureSpec, self).__init__()

        self._status = status

        self._name_section = name
        self._reach = None
        self._start_rk = None
        self._end_rk = None
        self._temperature = None

    @classmethod
    def _db_create(cls, execute, ext=""):
        execute(f"""
          CREATE TABLE initial_conditions_temperature_spec{ext}(
            {cls.create_db_add_pamhyr_id()},
            deleted BOOLEAN NOT NULL DEFAULT FALSE,
            ic_default INTEGER NOT NULL,
            name TEXT NOT NULL,
            reach INTEGER NOT NULL,
            start_rk REAL NOT NULL,
            end_rk REAL NOT NULL,
            temperature REAL NOT NULL,
            {Scenario.create_db_add_scenario()},
            {Scenario.create_db_add_scenario_fk()},
            FOREIGN KEY(ic_default)
              REFERENCES initial_conditions_temperature(pamhyr_id),
            FOREIGN KEY(reach) REFERENCES river_reach(pamhyr_id)
          )
        """)

        return cls._create_submodel(execute)

    @classmethod
    def _db_update(cls, execute, version, data=None):
        major, minor, release = version.strip().split(".")

        if major == "0":
            if int(minor) < 2 or (int(minor) == 2 and int(release) < 7):
                table_name = "initial_conditions_temperature_spec"
                if not cls.is_table_exists(execute, table_name):
                    cls._db_create(execute)

        return True

    @classmethod
    def _db_load(cls, execute, data=None):
        new = []
        status = data['status']
        reachs = data["edges"]
        scenario = data["scenario"]
        loaded = data['loaded_pid']

        if scenario is None:
            return new

        table = execute(
            "SELECT pamhyr_id, deleted, name, reach, start_rk, end_rk, " +
            "temperature, scenario " +
            "FROM initial_conditions_temperature_spec " +
            f"WHERE ic_default = {data['ic_default_id']} " +
            f"AND scenario = {scenario.id} " +
            f"AND pamhyr_id NOT IN ({', '.join(map(str, loaded))}) "
        )

        if table is not None:
            for row in table:
                it = iter(row)

                id = next(it)
                deleted = (next(it) == 1)
                name = next(it)
                reach = next(it)
                start_rk = next(it)
                end_rk = next(it)
                temperature = next(it)
                owner_scenario = next(it)

                new_spec = cls(
                    id=id, name=name,
                    status=status,
                    owner_scenario=owner_scenario
                )
                if deleted:
                    new_spec.set_as_deleted()

                new_spec.reach = reach
                new_spec.start_rk = start_rk
                new_spec.end_rk = end_rk
                new_spec.temperature = temperature

                # loaded.add(pid)
                new.append(new_spec)

        data["scenario"] = scenario.parent
        new += cls._db_load(execute, data)
        data["scenario"] = scenario

        return new

    def _db_save(self, execute, data=None):
        if not self.must_be_saved():
            return True

        ic_default = data['ic_default_id']

        sql = (
            "INSERT INTO " +
            "initial_conditions_temperature_spec(pamhyr_id, deleted, " +
            "ic_default, name, reach, " +
            "start_rk, end_rk, temperature, scenario) " +
            "VALUES (" +
            f"{self.id}, {self._db_format(self.is_deleted())}, " +
            f"{ic_default}, " +
            f"'{self._db_format(self._name_section)}', " +
            f"{self._reach}, " +
            f"{self._start_rk}, {self._end_rk}, " +
            f"{self._temperature}, " +
            f"{self._status.scenario_id}" +
            ")"
        )
        execute(sql)

        return True

    @property
    def name(self):
        return self._name_section

    @name.setter
    def name(self, name):
        self._name_section = name
        self._status.modified()

    @property
    def reach(self):
        return self._reach

    @reach.setter
    def reach(self, reach):
        self._reach = reach
        self._status.modified()

    @property
    def start_rk(self):
        return self._start_rk

    @start_rk.setter
    def start_rk(self, start_rk):
        self._start_rk = start_rk
        self._status.modified()

    @property
    def end_rk(self):
        return self._end_rk

    @end_rk.setter
    def end_rk(self, end_rk):
        self._end_rk = end_rk
        self._status.modified()

    @property
    def temperature(self):
        return self._temperature

    @temperature.setter
    def temperature(self, temperature):
        self._temperature = temperature
        self._status.modified()
