# REPLine.py -- Pamhyr
# Copyright (C) 2024-2025  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 functools import reduce

from tools import trace, timer

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


class REPLine(SQLSubModel):
    _sub_classes = []

    def __init__(self, id: int = -1, enabled=True,
                 name="", line="", solvers=set(),
                 status=None, owner_scenario=-1):
        super(REPLine, self).__init__(
            id, status=status,
            owner_scenario=owner_scenario
        )

        self._enabled = enabled
        self._name = f"Line #{self._pamhyr_id}" if name == "" else name
        self._line = line
        self._solvers = solvers

    def __getitem__(self, key):
        value = None

        if key == "enabled":
            value = self._enabled
        elif key == "name":
            value = self._name
        elif key == "line":
            value = self._line
        elif key == "solvers":
            value = self._solvers

        return value

    def __setitem__(self, key, value):
        if key == "enabled":
            self._enabled = value
        elif key == "name":
            self._name = value
        elif key == "line":
            self._line = value
        elif key == "solvers":
            self._solvers = value

        self._status.modified()

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

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

    def is_enabled(self):
        return self._enabled

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

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

    @property
    def line(self):
        return self._line

    @line.setter
    def line(self, line):
        self._line = line
        self._status.modified()

    @property
    def solvers(self):
        return self._solvers

    @solvers.setter
    def solvers(self, solvers):
        self._solvers = solvers
        self._status.modified()

    @classmethod
    def _db_create(cls, execute, ext=""):
        execute(f"""
          CREATE TABLE rep_lines{ext} (
            {cls.create_db_add_pamhyr_id()},
            enabled BOOLEAN NOT NULL,
            deleted BOOLEAN NOT NULL DEFAULT FALSE,
            name TEXT NOT NULL,
            line TEXT NOT NULL,
            solvers TEXT 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":
            if int(release) < 9:
                cls._db_create(execute)
                return True
            else:
                cls._db_update_to_0_0_14(execute, data)

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

        return True

    @classmethod
    def _db_update_to_0_0_14(cls, execute, data):
        table = "rep_lines"

        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, enabled, name, line, solvers, scenario) " +
            "SELECT pamhyr_id, enabled, name, line, solvers, 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):
        new = []
        scenario = data["scenario"]
        loaded = data['loaded_pid']

        if scenario is None:
            return new

        table = execute(
            "SELECT pamhyr_id, enabled, deleted, name, line, " +
            "solvers, scenario " +
            "FROM rep_lines " +
            f"WHERE scenario = {scenario.id} " +
            f"AND pamhyr_id NOT IN ({', '.join(map(str, loaded))})"
        )

        for row in table:
            it = iter(row)

            id = next(it)
            enabled = (next(it) == 1)
            deleted = (next(it) == 1)
            name = next(it)
            line = next(it)
            solvers = set(next(it).split(";;"))
            owner_scenario = next(it)

            f = cls(
                id=id, enabled=enabled,
                name=name, line=line, solvers=solvers,
                status=data['status'], owner_scenario=owner_scenario
            )
            if deleted:
                f.set_as_deleted()

            loaded.add(id)
            new.append(f)

        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

        solvers = ";;".join(self._solvers)

        execute(
            "INSERT INTO " +
            "rep_lines(pamhyr_id, enabled, deleted, " +
            "name, line, solvers, scenario) " +
            "VALUES (" +
            f"{self._pamhyr_id}, {self._enabled}, " +
            f"{self._db_format(self.is_deleted())}, " +
            f"'{self._db_format(self._name)}', " +
            f"'{self._db_format(self._line)}', " +
            f"'{self._db_format(solvers)}', " +
            f"{self._status.scenario_id}" +
            ")"
        )

        return True
