# Value.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 -*-

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


class BHSValue(SQLSubModel):
    _sub_classes = []
    _id_cnt = 0

    def __init__(self, id: int = -1, name: str = "",
                 type=float, value=0.0,
                 status=None, owner_scenario=-1):
        super(BHSValue, self).__init__(
            id=id, status=status,
            owner_scenario=owner_scenario
        )

        self._name = name
        self._type = type
        self._value = type(value)

    @classmethod
    def _db_create(cls, execute, ext=""):
        execute(f"""
          CREATE TABLE hydraulic_structures_basic_value{ext} (
            {cls.create_db_add_pamhyr_id()},
            name TEXT NOT NULL,
            type TEXT NOT NULL,
            value TEXT NOT NULL,
            bhs INTEGER,
            {Scenario.create_db_add_scenario()},
            {Scenario.create_db_add_scenario_fk()},
            FOREIGN KEY(bhs) REFERENCES hydraulic_structures_basic(id),
            PRIMARY KEY(pamhyr_id, scenario)
          )
        """)

        return cls._create_submodel(execute)

    @classmethod
    def _db_update(cls, execute, version, data=None):
        major, minor, release = version.strip().split(".")
        if major == minor == "0":
            if int(release) < 6:
                cls._db_create(execute)
                return True
            else:
                cls._db_update_to_0_2_0(execute, data)

        return cls._update_submodel(execute, version, data)

    @classmethod
    def _db_update_to_0_2_0(cls, execute, data):
        table = "hydraulic_structures_basic_value"
        bhs = data['id2pid']['hydraulic_structures_basic']

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

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

        execute(
            f"INSERT INTO {table}_tmp " +
            "(pamhyr_id, name, type, value, bhs, scenario) " +
            "SELECT pamhyr_id, name, type, value, bhs, scenario " +
            f"FROM {table}"
        )

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

    @classmethod
    def _db_update_to_0_2_0_set_bhs_pid(cls, execute, table, bhs):
        els = execute(
            f"SELECT pamhyr_id, bhs FROM {table}"
        )

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

            execute(
                f"UPDATE {table} " +
                f"SET bhs = {bhs[bhs_id]} " +
                f"WHERE pamhyr_id = {pid}"
            )

    @classmethod
    def _str_to_type(cls, type):
        res = str

        if type == "float":
            res = float
        elif type == "int":
            res = int
        elif type == "bool":
            res = bool

        return res

    @classmethod
    def _type_to_str(cls, type):
        res = "str"

        if type == float:
            res = "float"
        elif type == int:
            res = "int"
        elif type == bool:
            res = "bool"

        return res

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

        if scenario is None:
            return []

        table = execute(
            "SELECT pamhyr_id, name, type, value, scenario " +
            "FROM hydraulic_structures_basic_value " +
            f"WHERE bhs = '{bhs_id}' " +
            f"AND scenario = {scenario.id} " +
            f"AND pamhyr_id NOT IN ({', '.join(map(str, loaded))})"
        )

        for row in table:
            it = iter(row)

            pid = next(it)
            name = next(it)
            type = cls._str_to_type(next(it))
            value = next(it)
            owner_scenario = next(it)

            val = cls(
                id=pid, name=name,
                type=type, value=value,
                status=status, owner_scenario=owner_scenario
            )

            new.append(val)
            loaded.add(pid)

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

        return new

    def _db_save(self, execute, data=None):
        bhs_id = data["bhs_id"]

        execute(
            "INSERT INTO " +
            "hydraulic_structures_basic_value" +
            "(pamhyr_id, name, type, value, bhs, scenario) " +
            "VALUES (" +
            f"{self._pamhyr_id}, " +
            f"'{self._db_format(self._name)}', " +
            f"'{self._db_format(self._type_to_str(self._type))}', " +
            f"'{self._db_format(self._value)}', " +
            f"{bhs_id}, " +
            f"{self._status.scenario_id}"
            ")"
        )

        return True

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

    @property
    def type(self):
        return self._type

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        self._value = self._type(value)
        self.modified()
