# FrictionList.py -- Pamhyr
# Copyright (C) 2023-2026  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 copy import copy
from tools import trace, timer
from functools import reduce

from Model.Tools.PamhyrDB import SQLSubModel
from Model.Tools.PamhyrListExt import PamhyrModelList

from Model.Friction.Friction import Friction

logger = logging.getLogger()


class FrictionList(PamhyrModelList):
    _sub_classes = [
        Friction
    ]

    @classmethod
    def _db_update_0_0_1(cls, execute, version):
        execute("ALTER TABLE `section` RENAME TO `friction`")

    @classmethod
    def _db_update(cls, execute, version, data=None):
        if version == "0.0.0":
            cls._db_update_0_0_1(execute, version)

        return cls._update_submodel(execute, version, data)

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

        new._lst = Friction._db_load(
            execute, data
        )

        return new

    def _db_save(self, execute, data=None):
        frictions = self.lst

        reach = data["reach"]
        execute(
            f"DELETE FROM friction WHERE reach = {reach.id} " +
            f"AND scenario = {self._status.scenario_id}"
        )

        ok = True
        ind = 0
        for friction in frictions:
            data["ind"] = ind
            ok &= friction._db_save(execute, data=data)
            ind += 1

        return ok

    def _get_frictions_list(self):
        # Frictions list generator is type (int, Point) with the first
        # element the index of the Point in list
        return list(
            map(
                lambda p: p[1],
                sorted(
                    self._lst,
                    key=lambda p: p[0]
                )
            )
        )

    @property
    def frictions(self):
        return self.lst

    def new(self, reach, index):
        n = Friction(reach=reach, status=self._status)
        self._lst.insert(index, n)
        self._status.modified()
        return n

    def _splited_for(self, reach):
        new = FrictionList(status=self._status)

        rk_min, rk_max = reduce(
            lambda mm, p: (
                min(mm[0], p.rk),
                max(mm[1], p.rk)
            ),
            reach.reach.profiles,
            ((999 ** 100), -(999 ** 100))
        )

        frictions = list(
            filter(
                lambda f: ((rk_min <= f.begin_rk <= rk_max) or
                           (rk_min <= f.end_rk <= rk_max)),
                self._lst))

        for ind, friction in enumerate(frictions):
            n = friction.cloned_for(reach)

            new._lst.insert(ind, n)
            new._status.modified()

        return new
