# DIFAdisTSSpec.py -- Pamhyr
# Copyright (C) 2023-2026  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 DIFAdisTSSpec(SQLSubModel):
    _sub_classes = [
    ]
    _id_cnt = 0

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

        self._status = status

        self._method = method
        self._reach = None
        self._start_rk = None
        self._end_rk = None
        self._dif = None
        self._b = None
        self._c = None
        self._enabled = True

    @classmethod
    def _db_create(cls, execute, ext=""):
        execute(f"""
          CREATE TABLE dif_adists_spec{ext}(
            {cls.create_db_add_pamhyr_id()},
            deleted BOOLEAN NOT NULL DEFAULT FALSE,
            dif_default INTEGER NOT NULL,
            method TEXT NOT NULL,
            reach INTEGER NOT NULL,
            start_rk REAL NOT NULL,
            end_rk REAL NOT NULL,
            dif REAL NOT NULL,
            b REAL,
            c REAL,
            enabled BOOLEAN NOT NULL,
            {Scenario.create_db_add_scenario()},
            {Scenario.create_db_add_scenario_fk()},
            FOREIGN KEY(dif_default) REFERENCES dif_adists(id),
            FOREIGN KEY(reach) REFERENCES river_reach(id)
          )
        """)

        return cls._create_submodel(execute)

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

        if major == "0" and int(minor) < 2:
            if cls.is_table_exists(execute, "dif_spec"):
                cls._db_update_to_0_2_0(execute, data)
            else:
                cls._db_create(execute)

        return True

    @classmethod
    def _db_update_to_0_2_0(cls, execute, data):
        table = "dif_spec"
        table_new = "dif_adists_spec"
        reachs = data['id2pid']['river_reach']

        cls.update_db_add_pamhyr_id(execute, table, data)
        Scenario.update_db_add_scenario(execute, table)

        cls._db_create(execute, ext="_tmp")

        execute(
            f"INSERT INTO {table_new}_tmp " +
            "(pamhyr_id, dif_default, " +
            "method, reach, start_rk, end_rk, " +
            "dif, b, c, scenario) " +
            "SELECT pamhyr_id, dif_default, " +
            "method, reach, start_rk, end_rk, " +
            "dif, b, c, scenario " +
            f"FROM {table}"
        )

        execute(f"DROP TABLE {table}")
        execute(f"ALTER TABLE {table_new}_tmp RENAME TO {table_new}")

        cls._db_update_to_0_2_0_set_reach_pid(execute, table_new, reachs)
        cls._db_update_to_0_2_0_set_dif_pid(execute, data)

    @classmethod
    def _db_update_to_0_2_0_set_dif_pid(cls, execute, data):
        pid_dif = data["id2pid"]["dif_adists"]
        els = execute(
            "SELECT pamhyr_id, dif_default FROM dif_adists_spec"
        )

        for row in els:
            it = iter(row)
            pid = next(it)
            dif_id = next(it)

            if dif_id == -1:
                continue

            execute(
                f"UPDATE dif_adists_spec" +
                f"SET dif_default = {pid_dif[dif_id]} " +
                f"WHERE pamhyr_id = {pid}"
            )

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

        if scenario is None:
            return new

        table = execute(
            "SELECT pamhyr_id, deleted, method, reach, start_rk, end_rk, " +
            "dif, b, c, enabled, scenario " +
            "FROM dif_adists_spec " +
            f"WHERE dif_default = {data['dif_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)
                method = next(it)
                reach = next(it)
                start_rk = next(it)
                end_rk = next(it)
                dif = next(it)
                b = next(it)
                c = next(it)
                enabled = (next(it) == 1)
                owner_scenario = next(it)

                new_spec = cls(
                    id=id,
                    method=method,
                    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.dif = dif
                new_spec.b = b
                new_spec.c = c
                new_spec.enabled = enabled

                loaded.add(id)
                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

        dif_default = data['dif_default_id']

        sql = (
            "INSERT INTO " +
            "dif_adists_spec(pamhyr_id, deleted, " +
            "dif_default, method, reach, " +
            "start_rk, end_rk, dif, b, c, enabled, scenario) " +
            "VALUES (" +
            f"{self.id}, {self._db_format(self.is_deleted())}, " +
            f"{dif_default}, " +
            f"'{self._db_format(self._method)}', " +
            f"{self._reach}, " +
            f"{self._start_rk}, {self._end_rk}, " +
            f"{self._dif}, {self._b}, {self._c}, " +
            f"{self._enabled}, " +
            f"{self._status.scenario_id}" +
            ")"
        )
        execute(sql)

        return True

    @property
    def method(self):
        return self._method

    @method.setter
    def method(self, method):
        self._method = method
        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 dif(self):
        return self._dif

    @dif.setter
    def dif(self, dif):
        self._dif = dif
        self._status.modified()

    @property
    def b(self):
        return self._b

    @b.setter
    def b(self, b):
        self._b = b
        self._status.modified()

    @property
    def c(self):
        return self._c

    @c.setter
    def c(self, c):
        self._c = c
        self._status.modified()

    @property
    def enabled(self):
        return self._enabled

    @enabled.setter
    def enabled(self, enabled):
        self._enabled = enabled
        self._status.modified()
