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

from tools import trace, timer

from Model.Tools.PamhyrListExt import PamhyrModelList
from Model.Stricklers.Stricklers import Stricklers


class StricklersList(PamhyrModelList):
    _sub_classes = [
        Stricklers,
    ]

    @classmethod
    def _db_create(cls, execute):
        return cls._create_submodel(execute)

    @classmethod
    def _db_update(cls, execute, version, data=None):
        return cls._update_submodel(execute, version, data)

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

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

        return new

    def _db_save(self, execute, data=None):
        execute(
            "DELETE FROM stricklers " +
            f"WHERE scenario = {self._status.scenario_id}"
        )

        objs = self._lst
        return self._save_submodel(execute, objs, data)

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

    def new(self, index):
        s = Stricklers(
            status=self._status,
            owner_scenario=self._status.scenario_id
        )
        self.insert(index, s)
        self.modified()
        return s

    @timer
    def sort(self, reverse: bool = False, key=None):
        def f(st): return st.name
        if key is not None:
            f = key

        self._lst = sorted(
            self._lst,
            key=f,
            reverse=reverse,
        )

        self.modified()
