# D90AdisTSSpec.py -- Pamhyr
# Copyright (C) 2023-2024  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

logger = logging.getLogger()


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

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

        self._status = status

        if id == -1:
            self.id = D90AdisTSSpec._id_cnt
        else:
            self.id = id

        self._name_section = name
        self._reach = None
        self._start_rk = None
        self._end_rk = None
        self._d90 = None
        self._enabled = True

        D90AdisTSSpec._id_cnt = max(D90AdisTSSpec._id_cnt + 1, self.id)

    @classmethod
    def _db_create(cls, execute):
        execute("""
              CREATE TABLE d90_spec(
                id INTEGER NOT NULL PRIMARY KEY,
                d90_default INTEGER NOT NULL,
                name TEXT NOT NULL,
                reach INTEGER NOT NULL,
                start_rk REAL NOT NULL,
                end_rk REAL NOT NULL,
                d90 REAL NOT NULL,
                enabled BOOLEAN NOT NULL,
                FOREIGN KEY(d90_default) REFERENCES d90_adists(id),
                FOREIGN KEY(reach) REFERENCES river_reach(id)
              )
            """)

        return cls._create_submodel(execute)

    @classmethod
    def _db_update(cls, execute, version):
        major, minor, release = version.strip().split(".")
        if major == 0 and minor < 1:
            if int(release) < 6:
                cls._db_create(execute)

        return True

    @classmethod
    def _db_load(cls, execute, data=None):
        new = []

        table = execute(
            "SELECT id, d90_default, name, reach, start_rk, end_rk, " +
            "d90, enabled " +
            "FROM d90_spec " +
            f"WHERE d90_default = {data['d90_default_id']} "
        )

        if table is not None:
            for row in table:
                id = row[0]
                name = row[2]
                reach = row[3]
                start_rk = row[4]
                end_rk = row[5]
                d90 = row[6]
                enabled = (row[7] == 1)

                new_spec = cls(
                    id=id,
                    name=name,
                    status=data['status']
                )

                new_spec.reach = reach
                new_spec.start_rk = start_rk
                new_spec.end_rk = end_rk
                new_spec.d90 = d90
                new_spec.enabled = enabled

                new.append(new_spec)

        return new

    def _db_save(self, execute, data=None):
        d90_default = data['d90_default_id']

        sql = (
            "INSERT INTO " +
            "d90_spec(id, d90_default, name, reach, " +
            "start_rk, end_rk, d90, enabled) " +
            "VALUES (" +
            f"{self.id}, " +
            f"{d90_default}, " +
            f"'{self._db_format(self._name_section)}', " +
            f"{self._reach}, " +
            f"{self._start_rk}, " +
            f"{self._end_rk}, " +
            f"{self._d90}, " +
            f"{self._enabled}" +
            ")"
        )
        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 d90(self):
        return self._d90

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

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

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