# Status.py -- Pamhyr model status class
# 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 enum import Enum, auto

logger = logging.getLogger()


class Status(Enum):
    EDIT = auto()
    READ_ONLY = auto()


class StudyStatus(object):
    def __init__(self, scenario=None):
        super(StudyStatus, self).__init__()
        self._status = Status.EDIT
        self._scenario = scenario
        self._saved = True
        self._loading = False

    @property
    def scenario_id(self):
        if self._scenario is None:
            return -1

        return self._scenario.id

    def is_editable(self):
        return self._status == Status.EDIT

    def set_as_editable(self):
        self._status = Status.EDIT

    def is_read_only(self):
        return self._status == Status.READ_ONLY

    def set_as_read_only(self):
        self._status = Status.READ_ONLY

    @property
    def scenario(self):
        return self._scenario

    @scenario.setter
    def scenario(self, scenario):
        logger.debug(f"Set scenario to {scenario}")
        self._scenario = scenario

    @property
    def version(self):
        if self._scenario is None:
            return 0

        return self._scenario.revision

    @version.setter
    def version(self, version):
        if self._scenario is None:
            return

        self._scenario.revision = version

    def str_display(self):
        if self._scenario is None:
            return ""

        return f"{self._scenario.name}"

    def is_saved(self):
        return self._saved

    def is_loading(self):
        return self._loading

    def start_loading(self):
        self._loading = True

    def stop_loading(self):
        self._loading = False

    def save(self):
        logger.debug("model status set as saved")
        self._saved = True

    def _set_as_not_saved(self):
        self._saved = False

    def _set_as_saved(self):
        self._saved = True

    def modified(self):
        if self._loading:
            return

        if self._saved:
            self.version += 1

        self._set_as_not_saved()
