'''
/***************************************************************************
Name       :  geowrsi__settings_sos_controller.py
Description:  Controller for GeoWRSI SOS Tool
copyright  :  (C) 2020-2023 by FEWS
email      :  jhowton@contractor.usgs.gov
Author     :  Jacob Howton
Modified   :  mm/dd/yyyy - descripton - Description


 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
'''

import os

from PyQt5.QtWidgets import QDialog, QMessageBox

from fews_tools import fews_tools_config as config
from fews_tools.forms.Ui_SOSCalculationDefinition import Ui_SOSCalculationDefinition
from fews_tools.models.workspace_setup_model import WorkspaceSetupModel


class SOSController(QDialog):
    '''
    Class to set up the GeoWrsi SOS settings
    '''

    def __init__(self, sos_default_settings):
        QDialog.__init__(self)
        self.ui = Ui_SOSCalculationDefinition()
        self.ui.setupUi(self)

        self.wrksp_setup = WorkspaceSetupModel()
        self.settings_path = os.path.join(self.wrksp_setup.get_workspace(),
                                          config.PROGRAM_SETTINGS, 'geowrsi_settings.txt')
        self.sos_dic = sos_default_settings
        self.geowrsi_dic = {}

        self.__initial_form_load__()

        self.ui.okButton.clicked.connect(self.save_settings)
        self.ui.ignoreSOSClimatologyCheckBox.toggled.connect(
            self.hide_sos_clim)

    def __initial_form_load__(self):
        '''
        Load the GUI with the type of SOS Calculation and
        Crop Failure Definition
        '''

        sos_calculation_type = ["3-Period Rain Threshold"]

        self.ui.typeOfSOSCalculationComboBox.addItems(sos_calculation_type)

        crop_failure_definition = ["WRSI Threshold of"]

        self.ui.cropFailureDefinitionComboBox.addItems(crop_failure_definition)

        # Disable the spin box to lock the value to 40 like the
        # standalone version has it.
        self.ui.dontRestartAfterSpinBox.setDisabled(True)

        self.load_from_settings_dic()

    def save_settings(self):
        '''
        This function is called when ok is clicked on the GUI
        This  will assign any values that are not already set
        in the sos_dic file and then print the sos_dic to the
        ProgramSettings folder as geowrsi_settings.txt
        '''

        if self.ui.recalculateSOSCheckBox.isChecked():
            QMessageBox.warning(
                self,
                'Recalculate SOS Not Implemented.',
                'Recalculate SOS is not implemented yet, uncheck to continue.',
                QMessageBox.Ok)
            return

        self.sos_dic['type_of_sos_calculation'] = self.ui.typeOfSOSCalculationComboBox.currentText()
        self.sos_dic['period_1_rainfall'] = self.ui.period1RainfallSpinBox.value()
        self.sos_dic['period_2_3_rainfall'] = self.ui.period23RainfallSpinBox.value()
        self.sos_dic['ignore_sos_clim'] = self.ui.ignoreSOSClimatologyCheckBox.isChecked()
        self.sos_dic['max_periods_early'] = self.ui.maxPeriodsEarlySpinBox.value()
        self.sos_dic['max_periods_late'] = self.ui.maxPeriodsLateSpinBox.value()
        self.sos_dic['recalculate_sos_after_crop_failure'] = self.ui.recalculateSOSCheckBox.isChecked()
        self.sos_dic['crop_failure_definition_for_restart'] = self.ui.cropFailureDefinitionComboBox.currentText()
        self.sos_dic['crop_failure_definition_for_restart_percent'] = self.ui.cropFailureDefinitonPercentageSpinBox.value()
        self.sos_dic['dont_restart_after'] = self.ui.dontRestartAfterSpinBox.value()
        self.sos_dic['max_growing_periods_after_eos'] = self.ui.MaxGrowingPeriodsAfterEOSSpinBox.value()
        self.sos_dic['exclude_areas_less_than'] = self.ui.excludeAreasCheckBox.isChecked()
        self.sos_dic['exclude_areas_less_than_percent'] = self.ui.excludeAreasLessThanSpinBox.value()

        # For each dictionary pair in sos_dic either replace or append on
        # the existing geowrsi dictionary to not overwrite the sos settings
        for key, value in self.sos_dic.items():
            self.geowrsi_dic[key] = value

        with open(self.settings_path, "w") as f_obj:
            for key, value in self.geowrsi_dic.items():
                f_obj.write('%s %s\n' % (key, value))
        self.close()

    def hide_sos_clim(self):
        """
        Hides or shows the max periods early or late if
        the ignore sos climatology setting is checked or not
        """
        if self.ui.ignoreSOSClimatologyCheckBox.isChecked():
            self.ui.lblMaxPeriodsEarly.setVisible(False)
            self.ui.lblMaxPeriodsLate.setVisible(False)
            self.ui.maxPeriodsEarlySpinBox.setVisible(False)
            self.ui.maxPeriodsLateSpinBox.setVisible(False)

        else:
            self.ui.lblMaxPeriodsEarly.setVisible(True)
            self.ui.lblMaxPeriodsLate.setVisible(True)
            self.ui.maxPeriodsEarlySpinBox.setVisible(True)
            self.ui.maxPeriodsLateSpinBox.setVisible(True)

    def load_from_settings_dic(self):
        """
        Load the settings from the geowrsi settings file if it exists.
        """
        if os.path.exists(self.settings_path):
            with open(self.settings_path) as f_obj:
                for line in f_obj:
                    (key, value) = line.split(" ", 1)
                    try:
                        self.geowrsi_dic[key] = int(value[:-1])
                    except ValueError:
                        self.geowrsi_dic[key] = value[:-1]

        for key, value in self.geowrsi_dic.items():
            self.sos_dic[key] = value

        self.ui.typeOfSOSCalculationComboBox.setCurrentIndex(
            self.ui.typeOfSOSCalculationComboBox.findText(
                self.sos_dic['type_of_sos_calculation']))
        self.ui.period1RainfallSpinBox.setValue(
            self.sos_dic['period_1_rainfall'])
        self.ui.period23RainfallSpinBox.setValue(
            self.sos_dic['period_2_3_rainfall'])
        self.ui.ignoreSOSClimatologyCheckBox.setChecked(
            (self.sos_dic['ignore_sos_clim'] == "True"))
        self.ui.maxPeriodsEarlySpinBox.setValue(
            self.sos_dic['max_periods_early'])
        self.ui.maxPeriodsLateSpinBox.setValue(
            self.sos_dic['max_periods_late'])
        self.ui.recalculateSOSCheckBox.setChecked(
            (self.sos_dic['recalculate_sos_after_crop_failure'] == "True"))
        self.ui.cropFailureDefinitionComboBox.setCurrentIndex(
            self.ui.cropFailureDefinitionComboBox.findText(
                self.sos_dic['crop_failure_definition_for_restart']))
        self.ui.cropFailureDefinitonPercentageSpinBox.setValue(
            float(self.sos_dic['crop_failure_definition_for_restart_percent']))
        self.ui.dontRestartAfterSpinBox.setValue(
            float(self.sos_dic['dont_restart_after']))
        self.ui.MaxGrowingPeriodsAfterEOSSpinBox.setValue(
            self.sos_dic['max_growing_periods_after_eos'])
        self.ui.excludeAreasCheckBox.setChecked(
            self.sos_dic['exclude_areas_less_than'] == "True")
        self.ui.excludeAreasLessThanSpinBox.setValue(
            float(self.sos_dic['exclude_areas_less_than_percent']))
