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

logger = logging.getLogger()


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

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

        self._status = status

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

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

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

    @classmethod
    def _db_create(cls, execute):
        execute("""
                  CREATE TABLE d90_adists(
                    id INTEGER NOT NULL PRIMARY KEY,
                    name TEXT NOT NULL,
                    d90 REAL NOT NULL,
                    enabled BOOLEAN NOT NULL
                  )
                """)

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

        if table is not None:
            for row in table:
                d90_id = row[0]
                name = row[1]
                d90 = row[2]
                enabled = (row[3] == 1)

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

                D90.d90 = d90
                D90.enabled = enabled

                data['d90_default_id'] = d90_id
                D90._data = D90AdisTSSpec._db_load(execute, data)

                new.append(D90)

        return new

    def _db_save(self, execute, data=None):
        execute(f"DELETE FROM d90_adists WHERE id = {self.id}")

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

        sql = (
            "INSERT INTO " +
            "d90_adists(" +
            "id, name, d90, enabled" +
            ") " +
            "VALUES (" +
            f"{self.id}, '{self._db_format(self._name)}', " +
            f"{d90}, {self._enabled}" +
            ")"
        )

        execute(sql)

        data['d90_default_id'] = self.id
        execute(
            "DELETE FROM d90_spec " +
            f"WHERE d90_default = {self.id}"
        )

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

        return True

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

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

    @name.setter
    def name(self, name):
        self._name = name
        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()

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

    def delete(self, data):
        self._data = list(
            filter(
                lambda x: x not in data,
                self._data
            )
        )
        self._status.modified()

    def delete_i(self, indexes):
        for ind in indexes:
            del self._data[ind]
        self._status.modified()

    def insert(self, index, data):
        self._data.insert(index, data)
        self._status.modified()
