# Stricklers.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 -*-

from tools import trace, timer

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


class Stricklers(SQLSubModel):
    _sub_classes = []

    def __init__(self, id: int = -1,
                 name: str = "",
                 comment: str = "",
                 minor: float = 35.0,
                 medium: float = 15.0,
                 status=None, owner_scenario=-1):
        super(Stricklers, self).__init__(
            id=id, status=status,
            owner_scenario=owner_scenario
        )

        self._name = name
        self._comment = comment

        self._minor = minor
        self._medium = medium

    @classmethod
    def _db_create(cls, execute, ext=""):
        execute(f"""
          CREATE TABLE stricklers{ext} (
            {cls.create_db_add_pamhyr_id()},
            deleted BOOLEAN NOT NULL DEFAULT FALSE,
            name TEXT,
            comment TEXT,
            minor REAL NOT NULL,
            medium REAL NOT NULL,
            {Scenario.create_db_add_scenario()},
            {Scenario.create_db_add_scenario_fk()},
            PRIMARY KEY(pamhyr_id, scenario)
          )
        """)

        return cls._create_submodel(execute)

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

        if major == "0" and minor == "1":
            if int(release) < 2:
                execute(
                    "ALTER TABLE stricklers " +
                    "ADD COLUMN deleted BOOLEAN NOT NULL DEFAULT FALSE"
                )

        return cls._update_submodel(execute, version, data)

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

        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, comment, minor, medium, scenario) " +
            "SELECT pamhyr_id, name, comment, minor, medium, 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):
        stricklers = []
        status = data["status"]
        scenario = data["scenario"]
        loaded = data['loaded_pid']

        if scenario is None:
            return []

        table = execute(
            "SELECT pamhyr_id, deleted, " +
            "name, comment, minor, medium, scenario " +
            "FROM stricklers " +
            f"WHERE scenario = {scenario.id} " +
            f"AND pamhyr_id NOT IN ({', '.join(map(str, loaded))})"
        )

        if table is None:
            return None

        for row in table:
            it = iter(row)

            pid = next(it)
            deleted = (next(it) == 1)
            name = next(it)
            comment = next(it)
            minor = next(it)
            medium = next(it)
            owner_scenario = next(it)

            new = cls(
                id=pid, name=name, comment=comment,
                minor=minor, medium=medium,
                status=status, owner_scenario=owner_scenario
            )
            if deleted:
                new.set_as_deleted()

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

        data["scenario"] = scenario.parent
        stricklers += cls._db_load(execute, data)
        data["scenario"] = scenario

        return stricklers

    def _db_save(self, execute, data=None):
        if not self.must_be_saved():
            return True

        execute(
            "INSERT INTO " +
            "stricklers(pamhyr_id, deleted, " +
            "name, comment, minor, medium, scenario) " +
            "VALUES (" +
            f"{self.pamhyr_id}, " +
            f"{self._db_format(self.is_deleted())}, " +
            f"'{self._db_format(self.name)}', " +
            f"'{self._db_format(self.comment)}', " +
            f"{float(self.minor)}, {float(self.medium)}, " +
            f"{self._status.scenario_id}"
            ")"
        )

        return True

    def __str__(self):
        return f"{self.name} ({self._minor}, {self._medium})"

    @property
    def name(self):
        if self._name == "":
            return f"K #{self.pamhyr_id}"
        return self._name

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

    @property
    def comment(self):
        return self._comment

    @comment.setter
    def comment(self, comment):
        self._comment = comment
        self.modified()

    @property
    def minor(self):
        return self._minor

    @minor.setter
    def minor(self, minor):
        self._minor = float(minor)
        self.modified()

    @property
    def medium(self):
        return self._medium

    @medium.setter
    def medium(self, medium):
        self._medium = float(medium)
        self.modified()
