# D90AdisTS.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 functools import reduce

from tools import trace, timer, old_pamhyr_date_to_timestamp

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

from Model.D90AdisTS.D90AdisTSSpec import D90AdisTSSpec

logger = logging.getLogger()


class D90AdisTS(SQLSubModel):
    _sub_classes = [
        D90AdisTSSpec,
    ]

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

        self._status = status

        self._name = name
        self._d90 = None
        self._enabled = True
        self._data = []

    @classmethod
    def _db_create(cls, execute, ext=""):
        execute(f"""
          CREATE TABLE d90_adists{ext}(
            {cls.create_db_add_pamhyr_id()},
            deleted BOOLEAN NOT NULL DEFAULT FALSE,
            name TEXT NOT NULL,
            d90 REAL NOT NULL,
            enabled BOOLEAN NOT NULL,
            {Scenario.create_db_add_scenario()},
            {Scenario.create_db_add_scenario_fk()}
          )
        """)

        if ext != "":
            return True

        return cls._create_submodel(execute)

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

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

        if not created:
            return cls._update_submodel(execute, version, data)

        return True

    @classmethod
    def _db_update_to_0_2_0(cls, execute, data):
        table = "d90_adists"

        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}_tmp " +
            "(pamhyr_id, name, d90, enabled, scenario) " +
            "SELECT pamhyr_id, name, d90, enabled, scenario " +
            f"FROM {table}"
        )

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

    @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, name, d90, enabled, scenario " +
            "FROM d90_adists " +
            f"WHERE 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)

                pid = next(it)
                deleted = (next(it) == 1)
                name = next(it)
                value_d90 = next(it)
                enabled = (next(it) == 1)
                owner_scenario = next(it)

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

                d90.d90 = value_d90
                d90.enabled = enabled

                data['d90_default_id'] = pid
                d90._data = D90AdisTSSpec._db_load(execute, data)

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

        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

        execute(
            f"DELETE FROM d90_adists " +
            f"WHERE pamhyr_id = {self.id} " +
            f"AND scenario = {self._status.scenario_id} "
        )

        d90 = -1.
        if self.d90 is not None:
            d90 = self.d90

        execute(
            "INSERT INTO " +
            "d90_adists(" +
            "pamhyr_id, deleted, " +
            "name, d90, enabled, scenario" +
            ") " +
            "VALUES (" +
            f"{self.id}, {self._db_format(self.is_deleted())}, " +
            f"'{self._db_format(self._name)}', " +
            f"{d90}, {self._enabled}, {self._status.scenario_id}" +
            ")"
        )

        data['d90_default_id'] = self.id
        execute(
            "DELETE FROM d90_adists_spec " +
            f"WHERE d90_default = {self.id} " +
            f"AND scenario = {self._status.scenario_id} "
        )

        for d90_spec in self._data:
            d90_spec._db_save(execute, data)

        return True

    def _data_traversal(self,
                        predicate=lambda obj, data: True,
                        modifier=lambda obj, data: None,
                        data={}):
        if predicate(self, data):
            modifier(self, data)

        for d in self._data:
            d._data_traversal(predicate, modifier, data)

    def __len__(self):
        return len(self._data)

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

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

    @property
    def d90(self):
        return self._d90

    @d90.setter
    def d90(self, d90):
        self._d90 = d90
        self.modified()

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

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

    def new(self, index):
        n = D90AdisTSSpec(status=self._status)
        self._data.insert(index, n)
        self.modified()
        return n

    def delete(self, data):
        list(
            map(
                lambda x: x.set_as_deleted(),
                data
            )
        )
        self.modified()

    def delete_i(self, indexes):
        list(
            map(
                lambda e: e[1].set_as_deleted(),
                filter(
                    lambda e: e[0] in indexes,
                    enumerate(self._data)
                )
            )
        )
        self.modified()

    def insert(self, index, data):
        if data in self._data:
            self.undelete([data])
        else:
            self._data.insert(index, data)

        self.modified()

    def undelete(self, lst):
        for x in lst:
            x.set_as_not_deleted()

        self.modified()
