# HydraulicStructures.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 tools import trace, timer

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

from Model.HydraulicStructures.Basic.Value import (
    BHSValue
)

logger = logging.getLogger()


class BasicHS(SQLSubModel):
    _sub_classes = [
        BHSValue,
    ]
    _id_cnt = 0

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

        self._status = status

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

        self._name = name
        self._type = ""
        self._enabled = True
        self._data = []

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

    @classmethod
    def _db_create(cls, execute):
        execute("""
          CREATE TABLE hydraulic_structures_basic(
            id INTEGER NOT NULL PRIMARY KEY,
            name TEXT NOT NULL,
            type TEXT NOT NULL,
            enabled BOOLEAN NOT NULL,
            hs INTEGER,
            FOREIGN KEY(hs) REFERENCES hydraulic_structures(id)
          )
        """)

        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) < 6:
                cls._db_create(execute)

        return True

    @classmethod
    def _get_ctor_from_type(cls, t):
        from Model.HydraulicStructures.Basic.Types import (
            BHS_types, NotDefined,
        )

        res = NotDefined

        if t in BHS_types.keys():
            res = BHS_types[t]

        return res

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

        table = execute(
            "SELECT id, name, type, enabled, hs " +
            "FROM hydraulic_structures_basic " +
            f"WHERE hs = {data['hs_id']} "
        )

        for row in table:
            bhs_id = row[0]
            name = row[1]
            type = row[2]
            enabled = (row[3] == 1)
            hs_id = row[4]

            ctor = cls._get_ctor_from_type(type)
            bhs = ctor(
                id=bhs_id,
                name=name,
                status=data['status']
            )

            bhs.enabled = enabled

            data['bhs_id'] = bhs_id
            bhs._data = BHSValue._db_load(
                execute, data
            )

            new.append(bhs)

        return new

    def _db_save(self, execute, data=None):
        hs_id = data['hs_id']

        sql = (
            "INSERT INTO " +
            "hydraulic_structures_basic(id, name, type, enabled, hs) " +
            "VALUES (" +
            f"{self.id}, " +
            f"'{self._db_format(self._name)}', " +
            f"'{self._db_format(self._type)}', " +
            f"{self._db_format(self.enabled)}, " +
            f"{hs_id} " +
            ")"
        )
        execute(sql)

        data['bhs_id'] = self.id
        execute(
            "DELETE FROM hydraulic_structures_basic_value " +
            f"WHERE bhs = {self.id}"
        )

        for values in self._data:
            values._db_save(execute, data)

        return True

    def __len__(self):
        return len(self._data)

    @property
    def name(self):
        if self._name == "":
            return f"{self._type}{self.id + 1}"

        return self._name

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

    @property
    def type(self):
        return self._type

    @type.setter
    def type(self, type):
        self._type = type
        self._status.modified()

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

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

    @property
    def parameters(self):
        return self._data

    def convert(self, new_type):
        return new_type(id=self.id, name=self.name, status=self._status)
