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


class Friction(SQLSubModel):
    def __init__(self, name: str = "", status=None):
        super(Friction, self).__init__()

        self._status = status

        self._name = name
        self._edge = None
        self._begin_kp = 0.0
        self._end_kp = 0.0
        self._begin_strickler = None
        self._end_strickler = None

    @classmethod
    def _sql_create(cls, execute):
        execute("""
          CREATE TABLE friction(
            id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
            ind INTERGER NOT NULL,
            begin_kp REAL NOT NULL,
            end_kp REAL NOT NULL,
            reach INTEGER NOT NULL,
            begin_strickler INTERGER,
            end_strickler INTERGER,
            FOREIGN KEY(reach) REFERENCES river_reach(id),
            FOREIGN KEY(begin_strickler) REFERENCES stricklers(id),
            FOREIGN KEY(end_strickler) REFERENCES stricklers(id)
          )
        """)

        return True

    @classmethod
    def _sql_update(cls, execute, version):
        return True

    @classmethod
    def _sql_load(cls, execute, data=None):
        new = []
        reach = data["parent"]  # Reach object
        status = data["status"]
        stricklers = data["stricklers"].stricklers

        table = execute(
            "SELECT ind, begin_kp, end_kp, begin_strickler, end_strickler " +
            f"FROM friction WHERE reach = {reach.id}"
        )

        for _ in table:
            new.append(None)

        for row in table:
            ind = row[0]
            # Get stricklers
            bs = next(filter(lambda s: s.id == row[3], stricklers))
            es = next(filter(lambda s: s.id == row[4], stricklers))

            # Create friction
            sec = cls(status=status)
            sec.edge = reach
            sec.begin_kp = row[1]
            sec.end_kp = row[2]
            sec.begin_strickler = bs
            sec.end_strickler = es

            yield ind, sec

    def _sql_save(self, execute, data=None):
        ind = data["ind"]
        execute(
            "INSERT INTO " +
            "friction(ind, begin_kp, end_kp, " +
            "reach, begin_strickler, end_strickler) " +
            "VALUES (" +
            f"{ind}, {self._begin_kp}, {self._end_kp}, " +
            f"{self._edge.id}, " +
            f"{self._begin_strickler.id}, {self._end_strickler.id}" +
            ")"
        )

        return True

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

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

    @property
    def edge(self):
        return self._edge

    @edge.setter
    def edge(self, edge):
        self._edge = edge
        if (edge is not None and
            self._begin_kp == 0.0 and
                self._end_kp == 0.0):
            self._begin_kp = self._edge.reach.get_kp_min()
            self._end_kp = self._edge.reach.get_kp_max()
        self._status.modified()

    def has_edge(self):
        return self._edge is not None

    @property
    def begin_kp(self):
        return self._begin_kp

    @begin_kp.setter
    def begin_kp(self, begin_kp):
        if self._edge is None:
            self._begin_kp = begin_kp
        else:
            _min = self._edge.reach.get_kp_min()
            _max = self._edge.reach.get_kp_max()

            if _min <= begin_kp <= _max:
                self._begin_kp = begin_kp

        self._status.modified()

    @property
    def end_kp(self):
        return self._end_kp

    @end_kp.setter
    def end_kp(self, end_kp):
        if self._edge is None:
            self._end_kp = end_kp
        else:
            _min = self._edge.reach.get_kp_min()
            _max = self._edge.reach.get_kp_max()

            if _min <= end_kp <= _max:
                self._end_kp = end_kp

        self._status.modified()

    @property
    def begin_strickler(self):
        return self._begin_strickler

    @begin_strickler.setter
    def begin_strickler(self, strickler):
        self._begin_strickler = strickler
        self._status.modified()

    @property
    def end_strickler(self):
        return self._end_strickler

    @end_strickler.setter
    def end_strickler(self, strickler):
        self._end_strickler = strickler
        self._status.modified()
