# OutputRKAdists.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,
    old_pamhyr_date_to_timestamp,
    date_iso_to_timestamp,
    date_dmy_to_timestamp,
)

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

logger = logging.getLogger()


class OutputRKAdists(SQLSubModel):
    _sub_classes = []

    def __init__(self, id: int = -1, reach=None,
                 rk=None, title: str = "",  status=None,
                 owner_scenario=-1):
        super(OutputRKAdists, self).__init__(
            id=id, status=status,
            owner_scenario=owner_scenario
        )

        self._reach = reach
        self._rk = rk
        self._title = str(title)
        self._enabled = True

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

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

    @property
    def rk(self):
        return self._rk

    @rk.setter
    def rk(self, profile_id):
        self._rk = profile_id
        self._status.modified()

    @property
    def title(self):
        return self._title

    @title.setter
    def title(self, title):
        self._title = title
        self._status.modified()

    @classmethod
    def _db_create(cls, execute, ext=""):
        execute(f"""
          CREATE TABLE  output_rk_adists{ext}(
            {cls.create_db_add_pamhyr_id()},
            deleted BOOLEAN NOT NULL DEFAULT FALSE,
            reach INTEGER NOT NULL,
            rk REAL NOT NULL,
            title TEXT NOT NULL,
            {Scenario.create_db_add_scenario()},
            {Scenario.create_db_add_scenario_fk()},
            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, "OutputRKAdists"):
                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 = "OutputRKAdists"
        table_new = "output_rk_adists"
        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, reach, rk, title, scenario) " +
            "SELECT pamhyr_id, reach, rk, title, 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)

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

        # reach   = data["reach"]
        # profile = data["profile"]

        if scenario is None:
            return new

        table = execute(
            "SELECT pamhyr_id, deleted, reach, rk, title, scenario " +
            f"FROM  output_rk_adists"
        )

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

                pid = next(it)
                deleted = (next(it) == 1)
                id_reach = next(it)
                id_rk = next(it)
                title = next(it)
                owner_scenario = next(it)

                new_output = cls(
                    id=pid, reach=id_reach,
                    rk=id_rk, title=title,
                    status=status,
                    owner_scenario=owner_scenario,
                )
                if deleted:
                    new_output.set_as_deleted()

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

        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(
            "DELETE FROM output_rk_adists " +
            f"WHERE pamhyr_id = {self.id} " +
            f"AND scenario = {self._status.scenario_id} "
        )

        execute(
            "INSERT INTO " +
            "output_rk_adists(pamhyr_id, deleted, " +
            "reach, rk, title, scenario) " +
            "VALUES (" +
            f"{self.id}, {self._db_format(self.is_deleted())}, " +
            f"{self._reach}, {self._rk}, " +
            f"'{self._db_format(self._title)}', " +
            f"{self._status.scenario_id}" +
            ")"
        )

        return True

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

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