# AddFile.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 AddFile(SQLSubModel):
    _sub_classes = []
    _id_cnt = 0

    def __init__(self, id: int = -1, enabled=True,
                 name="", path="", text="",
                 status=None):
        super(AddFile, self).__init__()

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

        self._status = status

        self._enabled = enabled
        self._name = f"File {self.id}" if name == "" else name
        self._path = path
        self._text = text

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

    def __getitem__(self, key):
        value = None

        if key == "enabled":
            value = self._enabled
        elif key == "name":
            value = self._name
        elif key == "path":
            value = self._path
        elif key == "text":
            value = self._text

        return value

    def __setitem__(self, key, value):
        if key == "enabled":
            self._enabled = value
        elif key == "name":
            self._name = value
        elif key == "path":
            self._path = value
        elif key == "text":
            self._text = 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 path(self):
        return self._path

    @path.setter
    def path(self, path):
        self._path = path
        self._status.modified()

    @property
    def text(self):
        return self._text

    @text.setter
    def text(self, text):
        self._text = text
        self._status.modified()

    @classmethod
    def _db_create(cls, execute):
        execute("""
          CREATE TABLE additional_files(
            id INTEGER NOT NULL PRIMARY KEY,
            enabled BOOLEAN NOT NULL,
            name TEXT NOT NULL,
            path TEXT NOT NULL,
            text 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) < 8:
                cls._db_create(execute)

        return True

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

        table = execute(
            "SELECT id, enabled, name, path, text " +
            "FROM additional_files"
        )

        for row in table:
            it = iter(row)

            id = next(it)
            enabled = (next(it) == 1)
            name = next(it)
            path = next(it)
            text = next(it)

            f = cls(
                id=id, enabled=enabled, name=name, path=path, text=text,
                status=data['status']
            )

            new.append(f)

        return new

    def _db_save(self, execute, data=None):
        sql = (
            "INSERT INTO " +
            "additional_files(id, enabled, name, path, text) " +
            "VALUES (" +
            f"{self.id}, {self._enabled}, " +
            f"'{self._db_format(self._name)}', " +
            f"'{self._db_format(self._path)}', " +
            f"'{self._db_format(self._text)}'" +
            ")"
        )
        execute(sql)

        return True
