# DIFAdisTS.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.DIFAdisTS.DIFAdisTSSpec import DIFAdisTSSpec

logger = logging.getLogger()


class DIFAdisTS(SQLSubModel):
    _sub_classes = [
        DIFAdisTSSpec,
    ]
    _id_cnt = 0

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

        self._status = status

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

        self._name = name
        self._method = None
        self._dif = None
        self._b = None
        self._c = None
        self._enabled = True
        self._types = ["iwasa", "fisher", "elder", "constante", "generique"]
        self._data = []

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

    @classmethod
    def _db_create(cls, execute):
        execute("""
                  CREATE TABLE dif_adists(
                    id INTEGER NOT NULL PRIMARY KEY,
                    name TEXT NOT NULL,
                    method TEXT NOT NULL,
                    dif REAL NOT NULL,
                    b REAL,
                    c REAL,
                    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, method, dif, b, c, enabled " +
            "FROM dif_adists"
        )

        if table is not None:
            for row in table:
                dif_id = row[0]
                name = row[1]
                method = row[2]
                dif = row[3]
                b = row[4]
                c = row[5]
                enabled = (row[6] == 1)

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

                DIF.method = method
                DIF.dif = dif
                DIF.b = b
                DIF.c = c
                DIF.enabled = enabled

                data['dif_default_id'] = dif_id
                DIF._data = DIFAdisTSSpec._db_load(execute, data)

                new.append(DIF)

        return new

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

        method = ""
        if self.method is not None:
            method = self.method

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

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

        c = -1.
        if self.dif is not None:
            c = self.c

        sql = (
            "INSERT INTO " +
            "dif_adists(" +
            "id, name, method, dif, b, c, enabled" +
            ") " +
            "VALUES (" +
            f"{self.id}, '{self._db_format(self._name)}', " +
            f"'{self._db_format(self._method)}', " +
            f"{dif}, {b}, {c}, {self._enabled}" +
            ")"
        )

        execute(sql)

        data['dif_default_id'] = self.id
        execute(
            "DELETE FROM dif_spec " +
            f"WHERE dif_default = {self.id}"
        )

        for dif_spec in self._data:
            dif_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 method(self):
        return self._method

    @method.setter
    def method(self, method):
        self._method = method
        self._status.modified()

    @property
    def types(self):
        return self._types

    @property
    def dif(self):
        return self._dif

    @dif.setter
    def dif(self, dif):
        self._dif = dif
        self._status.modified()

    @property
    def b(self):
        return self._b

    @b.setter
    def b(self, b):
        self._b = b
        self._status.modified()

    @property
    def c(self):
        return self._c

    @c.setter
    def c(self, c):
        self._c = c
        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 = DIFAdisTSSpec(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()
