'''
/***************************************************************************
Name       :  geowrsi_output_settings_controller.py
Description:  Ouput Settings Controller for GeoWRSI Tool
copyright  :  (C) 2022-2023 by FEWS
email      :  dhackman@contractor.usgs.gov
Created    :  10/07/2022
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, QFileDialog, QMessageBox

from fews_tools.forms.Ui_GeoWRSIOutputOptions import Ui_OutputOptions
from fews_tools.models.workspace_setup_model import WorkspaceSetupModel

from fews_tools import fews_tools_config as config
from fews_tools.utilities import geoclim_utilities as util
from fews_tools.utilities import geowrsi_utilities as geo_util


class GeoWRSIOutputSettings(QDialog):
    '''
    Class to set up the GeoWrsi output settings
    '''

    def __init__(self):
        QDialog.__init__(self)
        self.ui = Ui_OutputOptions()
        self.ui.setupUi(self)
        self.wrksp_setup = WorkspaceSetupModel()
        self.output_loc = self.wrksp_setup.get_output_path()
        self.file_path =\
            os.path.join(self.wrksp_setup.get_workspace(),
                         config.PROGRAM_SETTINGS,
                         config.GEOWRSI_OUT_SETTINGS_FILE)
        self.output_dic = geo_util.get_default_output_dic()
        self.output_dic['output_directory'] = self.output_loc
        self.current_outputs_list = []
        self.eos_outputs_list = []
        # Initial form load
        self.__initial_form_load__()
        # Button functionality on click toggle boxes
        self.ui.selectAllCurrentOutputsButton.clicked.connect(
            self.select_all_current)
        self.ui.selectAllEOSOutputsButton.clicked.connect(self.select_all_eos)
        self.ui.saveAllFilesAtCheckBox.toggled.connect(self.set_dek_spin_box)
        self.ui.outputBrowseButton.clicked.connect(self.browse_data_path)
        # Okay button clicked then save to file
        self.ui.okButton.clicked.connect(self.save_settings)

    def __initial_form_load__(self):
        '''
        Load the output setings GUI with the text options and overall setup
        '''
        self.fill_current_list()
        self.fill_eos_list()
        # Check for existing config.GEOWRSI_OUT_SETTINGS_FILE file
        self.output_dic = geo_util.set_output_dic_from_file(
            self.file_path, self.output_dic)
        self.set_from_dic()
        # Used to hide all of these for now, since we do not use
        # or know what all of these are used for
        self.setWindowTitle("GeoWRSI Output Options "
                            "(Disabled Sections Are Not Yet Implemented)")
        self.ui.saveAllFilesAtCheckBox.setEnabled(False)
        self.ui.givenPeriodSpinBox.setEnabled(False)

    def set_from_dic(self):
        '''
        Used to set the defaults based on the output_dic which has default
        values for now, but if the config.GEOWRSI_OUT_SETTINGS_FILE file
        exists, it will then be filled with those values
        '''
        # Current Period Outputs
        self.ui.currentWRSICheckBox.setChecked(self.output_dic['current_wrsi'])
        self.ui.currentWRSIAnomalyCheckBox.setChecked(
            self.output_dic['current_wrsi_anomaly'])
        self.ui.currentLGPCheckBox.setChecked(
            self.output_dic['current_lgp_phenology'])
        self.ui.currentSWICheckBox.setChecked(
            self.output_dic['current_soil_water_index'])
        self.ui.currentWatReqCheckBox.setChecked(
            self.output_dic['current_water_req_totals'])
        self.ui.currentMaxWaterDeficitsCheckBox.setChecked(
            self.output_dic['current_max_water_deficits'])
        self.ui.currentWaterDeficitCheckBox.setChecked(
            self.output_dic['current_water_deficit_totals'])
        self.ui.currentMaxWaterSurplusCheckBox.setChecked(
            self.output_dic['current_max_water_surplus'])
        self.ui.currentWaterSurplusCheckBox.setChecked(
            self.output_dic['current_water_surplus_totals'])
        self.ui.currentAETTotalsCheckBox.setChecked(
            self.output_dic['current_aet_totals'])
        # EOS Period Outputs
        self.ui.EOSWRSICheckBox.setChecked(self.output_dic['eos_wrsi'])
        self.ui.EOSWRSIAnomalyCheckBox.setChecked(
            self.output_dic['eos_wrsi_anomaly'])
        self.ui.EOSLGPCheckBox.setChecked(self.output_dic['eos_lgp_phenology'])
        self.ui.EOSSWICheckBox.setChecked(
            self.output_dic['eos_soil_water_index'])
        self.ui.EOSWatReqTotalsCheckBox.setChecked(
            self.output_dic['eos_water_req_totals'])
        self.ui.EOSMaxWaterDeficitsCheckBox.setChecked(
            self.output_dic['eos_max_water_deficits'])
        self.ui.EOSWaterDeficitCheckBox.setChecked(
            self.output_dic['eos_water_deficit_totals'])
        self.ui.EOSMaxWaterSurplusCheckBox.setChecked(
            self.output_dic['eos_max_water_surplus'])
        self.ui.EOSWaterSurplusCheckBox.setChecked(
            self.output_dic['eos_water_surplus_totals'])
        self.ui.EOSAETTotalsCheckBox.setChecked(
            self.output_dic['eos_aet_totals'])
        # Output Directory
        self.ui.outputBrowseButton.setEnabled(True)
        self.ui.outputDirLineEdit.setText(self.output_dic['output_directory'])
        self.ui.outputDirLineEdit.setEnabled(False)
        # Outputs to save at every period
        self.ui.everyPeriodWRSICheckBox.setChecked(
            self.output_dic['save_every_wrsi'])
        self.ui.everyPeriodLGPCheckBox.setChecked(
            self.output_dic['save_every_lgp_phenology'])
        self.ui.everyPeriodSWICheckBox.setChecked(
            self.output_dic['save_every_soil_water_index'])
        # Others
        self.ui.saveAllFilesAtCheckBox.setChecked(
            self.output_dic['save_all_files_at_given'])
        self.ui.givenPeriodSpinBox.setValue(
            int(self.output_dic['given_period']))
        self.set_dek_spin_box()
        self.ui.saveCropStageTotalsatEOSCheckBox.setChecked(
            self.output_dic['save_crop_stage_totals_eos'])
        # Need to fill the font, size and style combo boxes when loading form

    def fill_current_list(self):
        '''
        Used to append all the check boxes for the current outputs to a list
        '''
        self.current_outputs_list.append(self.ui.currentWRSICheckBox)
        self.current_outputs_list.append(self.ui.currentWRSIAnomalyCheckBox)
        self.current_outputs_list.append(self.ui.currentLGPCheckBox)
        self.current_outputs_list.append(self.ui.currentSWICheckBox)
        self.current_outputs_list.append(self.ui.currentWatReqCheckBox)
        self.current_outputs_list.append(
            self.ui.currentMaxWaterDeficitsCheckBox)
        self.current_outputs_list.append(self.ui.currentWaterDeficitCheckBox)
        self.current_outputs_list.append(
            self.ui.currentMaxWaterSurplusCheckBox)
        self.current_outputs_list.append(self.ui.currentWaterSurplusCheckBox)
        self.current_outputs_list.append(self.ui.currentAETTotalsCheckBox)

    def fill_eos_list(self):
        '''
        Used to append all the check boxes for the eos outputs to a list
        '''
        self.eos_outputs_list.append(self.ui.EOSWRSICheckBox)
        self.eos_outputs_list.append(self.ui.EOSWRSIAnomalyCheckBox)
        self.eos_outputs_list.append(self.ui.EOSLGPCheckBox)
        self.eos_outputs_list.append(self.ui.EOSSWICheckBox)
        self.eos_outputs_list.append(self.ui.EOSWatReqTotalsCheckBox)
        self.eos_outputs_list.append(self.ui.EOSMaxWaterDeficitsCheckBox)
        self.eos_outputs_list.append(self.ui.EOSWaterDeficitCheckBox)
        self.eos_outputs_list.append(self.ui.EOSMaxWaterSurplusCheckBox)
        self.eos_outputs_list.append(self.ui.EOSWaterSurplusCheckBox)
        self.eos_outputs_list.append(self.ui.EOSAETTotalsCheckBox)
        self.eos_outputs_list.append(self.ui.saveCropStageTotalsatEOSCheckBox)

    def select_all_current(self):
        '''
        Set checked to true for all current dekad outputs
        '''
        if self.ui.selectAllCurrentOutputsButton.text() ==\
                "Select All Current Outputs":
            for check_box in self.current_outputs_list:
                check_box.setChecked(True)
            self.ui.selectAllCurrentOutputsButton.setText(
                "Deselect All Current Outputs")
        else:
            for check_box in self.current_outputs_list:
                check_box.setChecked(False)
            self.ui.selectAllCurrentOutputsButton.setText(
                "Select All Current Outputs")

    def select_all_eos(self):
        '''
        Set checked to true for all current dekad outputs
        '''
        if self.ui.selectAllEOSOutputsButton.text() ==\
                "Select All EOS Outputs":
            for check_box in self.eos_outputs_list:
                check_box.setChecked(True)
            self.ui.selectAllEOSOutputsButton.setText(
                "Deselect All EOS Outputs")
        else:
            for check_box in self.eos_outputs_list:
                check_box.setChecked(False)
            self.ui.selectAllEOSOutputsButton.setText(
                "Select All EOS Outputs")

    def set_dek_spin_box(self):
        '''
        Enable/disable spin box based on check box
        '''
        if self.ui.saveAllFilesAtCheckBox.isChecked():
            self.ui.givenPeriodSpinBox.setEnabled(True)
        else:
            self.ui.givenPeriodSpinBox.setEnabled(False)

    def browse_data_path(self):
        '''
        Browse to output folder.
        '''
        output_path = QFileDialog.getExistingDirectory(
            self, 'Select Data Location', self.output_loc)
        if output_path:
            self.ui.outputDirLineEdit.setText(
                self.wrksp_setup.fix_os_sep_in_path(output_path))

    def save_settings(self):
        '''
        Function to save the settings when Ok button is clicked
        '''
        self.output_dic['current_wrsi'] =\
            self.ui.currentWRSICheckBox.isChecked()
        self.output_dic['current_wrsi_anomaly'] =\
            self.ui.currentWRSIAnomalyCheckBox.isChecked()
        self.output_dic['current_lgp_phenology'] =\
            self.ui.currentLGPCheckBox.isChecked()
        self.output_dic['current_soil_water_index'] =\
            self.ui.currentSWICheckBox.isChecked()
        self.output_dic['current_water_req_totals'] =\
            self.ui.currentWatReqCheckBox.isChecked()
        self.output_dic['current_max_water_deficits'] =\
            self.ui.currentMaxWaterDeficitsCheckBox.isChecked()
        self.output_dic['current_water_deficit_totals'] =\
            self.ui.currentWaterDeficitCheckBox.isChecked()
        self.output_dic['current_max_water_surplus'] =\
            self.ui.currentMaxWaterSurplusCheckBox.isChecked()
        self.output_dic['current_water_surplus_totals'] =\
            self.ui.currentWaterSurplusCheckBox.isChecked()
        self.output_dic['current_aet_totals'] =\
            self.ui.currentAETTotalsCheckBox.isChecked()

        self.output_dic['eos_wrsi'] =\
            self.ui.EOSWRSICheckBox.isChecked()
        self.output_dic['eos_wrsi_anomaly'] =\
            self.ui.EOSWRSIAnomalyCheckBox.isChecked()
        self.output_dic['eos_lgp_phenology'] =\
            self.ui.EOSLGPCheckBox.isChecked()
        self.output_dic['eos_soil_water_index'] =\
            self.ui.EOSSWICheckBox.isChecked()
        self.output_dic['eos_water_req_totals'] =\
            self.ui.EOSWatReqTotalsCheckBox.isChecked()
        self.output_dic['eos_max_water_deficits'] =\
            self.ui.EOSMaxWaterDeficitsCheckBox.isChecked()
        self.output_dic['eos_water_deficit_totals'] =\
            self.ui.EOSWaterDeficitCheckBox.isChecked()
        self.output_dic['eos_max_water_surplus'] =\
            self.ui.EOSMaxWaterSurplusCheckBox.isChecked()
        self.output_dic['eos_water_surplus_totals'] =\
            self.ui.EOSWaterSurplusCheckBox.isChecked()
        self.output_dic['eos_aet_totals'] =\
            self.ui.EOSAETTotalsCheckBox.isChecked()

        self.output_dic['output_directory'] =\
            self.ui.outputDirLineEdit.text()

        self.output_dic['save_every_wrsi'] =\
            self.ui.everyPeriodWRSICheckBox.isChecked()
        self.output_dic['save_every_lgp_phenology'] =\
            self.ui.everyPeriodLGPCheckBox.isChecked()
        self.output_dic['save_every_soil_water_index'] =\
            self.ui.everyPeriodSWICheckBox.isChecked()

        self.output_dic['save_all_files_at_given'] =\
            self.ui.saveAllFilesAtCheckBox.isChecked()
        self.output_dic['given_period'] =\
            self.ui.givenPeriodSpinBox.value()
        self.output_dic['save_crop_stage_totals_eos'] =\
            self.ui.saveCropStageTotalsatEOSCheckBox.isChecked()

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