# FrictionList.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 -*-

import logging

from copy import copy
from tools import trace, timer

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

from Model.Friction.Friction import Friction

logger = logging.getLogger()


class FrictionList(PamhyrModelList):
    _sub_classes = [
        Friction
    ]

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

    @classmethod
    def _sql_update(cls, execute, version):
        if version == "0.0.0":
            logger.info(f"Update friction TABLE from {version}")
            cls._sql_update_0_0_1(execute, version)

        return True

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

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

        return new

    def _sql_save(self, execute, data=None):
        reach = data["reach"]
        execute(f"DELETE FROM friction WHERE reach = {reach.id}")

        ok = True
        ind = 0
        for friction in self._lst:
            data["ind"] = ind
            ok &= friction._sql_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 lst(self):
        if not isinstance(self._lst, list):
            self._lst = self._get_frictions_list()

        return self._lst

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

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