# Results.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/>.

import logging
import numpy as np
import os

from copy import deepcopy
from datetime import datetime

from Model.Tools.PamhyrDB import SQLSubModel
from Model.Results.River.RiverAdisTS import River

logger = logging.getLogger()


class Results(SQLSubModel):
    def __init__(self, study=None, solver=None,
                 repertory="", name="0", type_pol=None):
        self._study = study
        self._solver = solver
        self._repertory = repertory
        self._name = name

        self._river = River(self._study)

        self._meta_data = {
            # Keep results creation date
            "creation_date": datetime.now(),
        }
        filelist = [f for f in os.listdir(self._repertory)
                    if os.path.isfile(os.path.join(self._repertory, f))
                    ]
        self._pollutants_list = [f[0:-4] for f in filelist if f[-4:] == ".bin"]
        self._pollutants_list.insert(0, self._pollutants_list.pop(
            self._pollutants_list.index("total_sediment"))
        )

        self._phys_var_list = ["C", "G", "M", "D", "L", "N", "R"]

        if solver is not None:
            self.set("solver_type", solver._type)

    @property
    def date(self):
        date = self._meta_data["creation_date"]
        return f"{date.isoformat(sep=' ')}"

    @property
    def river(self):
        return self._river

    @property
    def study(self):
        return self._study

    @property
    def pollutants_list(self):
        return self._pollutants_list

    @property
    def phys_var_list(self):
        return self._phys_var_list

    @property
    def nb_pollutants(self):
        return len(self._pollutants_list)

    def set(self, key, value):
        self._meta_data[key] = value

    def get(self, key):
        return self._meta_data[key]

    def reload(self):
        return self._solver.results(
            self._study,
            self._repertory,
            qlog=None,
        )

    def _db_save(self, execute, data=None):
        return False
