# REPLine.py -- Pamhyr
# Copyright (C) 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 -*-

from functools import reduce

from tools import trace, timer

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


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

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

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

        self._status = status

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

        REPLine._id_cnt = max(id, REPLine._id_cnt+1)

    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):
        execute("""
          CREATE TABLE rep_lines(
            id INTEGER NOT NULL PRIMARY KEY,
            enabled BOOLEAN NOT NULL,
            name TEXT NOT NULL,
            line TEXT NOT NULL,
            solvers TEXT NOT NULL
          )
        """)

        return cls._create_submodel(execute)

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

        return True

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

        table = execute(
            "SELECT id, enabled, name, line, solvers " +
            "FROM rep_lines"
        )

        for row in table:
            it = iter(row)

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

            f = cls(
                id=id, enabled=enabled, name=name, line=line,
                solvers=solvers, status=data['status']
            )

            new.append(f)

        return new

    def _db_save(self, execute, data=None):
        solvers = ";;".join(self._solvers)

        sql = (
            "INSERT INTO " +
            "rep_lines(id, enabled, name, line, solvers) " +
            "VALUES (" +
            f"{self.id}, {self._enabled}, " +
            f"'{self._db_format(self._name)}', " +
            f"'{self._db_format(self._line)}', " +
            f"'{self._db_format(solvers)}'" +
            ")"
        )
        execute(sql)

        return True
