'''
/***************************************************************************
Name	   :  datasets_controller.py
Description:  Datasets controller class for FEWSTools plugin,
              updated from QGIS2
copyright  :  (C) 2019-2023 by FEWS
email      :  minxuansun@contractor.usgs.gov
Modified   :  11/19/2019 - cholen - Fixed bug in __validate_text_inputs__
              07/13/2020 - cholen - Update to use util to fill ds control
              08/14/2020 - cholen - Fix regex check, more util
              10/08/2020 - cholen - Fix os sep in browse functions
              12/17/2020 - cholen - Date format additions/updates
              02/01/2021 - cholen - Check for date mis-match
              05/17-2021 - cholen - Match suffix and missing value for data-avg
              04/05/2022 - cholen - Add tiff support, update line edit checks.
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/
'''

from PyQt5.QtWidgets import QMessageBox, QDialog, QFileDialog

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

from fews_tools.models.datasets_model import DatasetsModel
from fews_tools.controllers.new_name_controller import NewNameController
from fews_tools.models.workspace_setup_model import WorkspaceSetupModel
from fews_tools.forms.Ui_DatasetDefinition import Ui_DatasetDefinition


class DatasetsController(QDialog):
    '''
    Class for datasets controller
    '''
    def __init__(self):
        QDialog.__init__(self)
        self.ui = Ui_DatasetDefinition()
        self.ui.setupUi(self)
        # get a list to hold widget values
        self.widget_val_list = [''] * 27

        self.ds_info = DatasetsModel()
        self.wrksp_setup = WorkspaceSetupModel()

        self.data_loc = self.wrksp_setup.get_climate_data_path()

        # will track changes to form for 'save'
        self.ui.datatypeComboBox.currentIndexChanged['QString'].connect(
            self.save_enabled)
        self.ui.dataextentComboBox.currentIndexChanged['QString'].connect(
            self.save_enabled)
        self.ui.datafolderLineEdit.textChanged.connect(self.save_enabled)
        self.ui.dataprefixLineEdit.textChanged.connect(self.save_enabled)
        self.ui.datadateComboBox.currentIndexChanged['QString'].connect(
            self.save_enabled)
        self.ui.fileSuffixComboBox.currentIndexChanged['QString'].connect(
            self.save_enabled)
        self.ui.missingSpinBox.valueChanged.connect(self.save_enabled)
        self.ui.avgdataLineEdit.textChanged.connect(self.save_enabled)
        self.ui.avgprefixLineEdit.textChanged.connect(self.save_enabled)
        self.ui.avgComboBox.currentIndexChanged['QString'].connect(
            self.save_enabled)
        self.ui.avgFileSuffixComboBox.currentIndexChanged['QString'].connect(
            self.save_enabled)
        self.ui.avgMissingSpinBox.valueChanged.connect(
            self.save_enabled)
        self.ui.ftphostLineEdit.textChanged.connect(self.save_enabled)
        self.ui.ftpdirLineEdit.textChanged.connect(self.save_enabled)
        self.ui.usernameLineEdit.textChanged.connect(self.save_enabled)
        self.ui.passLineEdit.textChanged.connect(self.save_enabled)
        self.ui.ftpfiledateComboBox.currentIndexChanged['QString'].connect(
            self.save_enabled)
        self.ui.ftpfileprefixLineEdit.textChanged.connect(self.save_enabled)
        self.ui.zipSuffixComboBox.currentIndexChanged['QString'].connect(
            self.save_enabled)
        self.ui.projectionComboBox.currentIndexChanged['QString'].connect(
            self.save_enabled)
        self.ui.uncompprefixLineEdit.textChanged.connect(self.save_enabled)
        self.ui.uncomprSuffixComboBox.currentIndexChanged['QString'].connect(
            self.save_enabled)
        self.ui.uncompdateComboBox.currentIndexChanged['QString'].connect(
            self.save_enabled)
        self.ui.defaultDSComboBox.currentIndexChanged['QString'].connect(
            self.save_enabled)
        self.ui.scaleFactorSpinBox.valueChanged.connect(self.save_enabled)
        self.ui.isFileCompressedCheckBox.toggled.connect(self.update_compression_info)

        # connect remaining widgets
        self.ui.datasetComboBox.currentIndexChanged['QString'].connect(
            self.dataset_selection_changed)
        self.ui.periodComboBox.currentIndexChanged['QString'].connect(
            self.select_periodicity)
        self.ui.copyButton.clicked.connect(self.match_data_avg_paths)
        self.ui.dataBrowseButton.clicked.connect(self.browse_data_path)
        self.ui.avgBrowseButton.clicked.connect(self.browse_avg_path)
        self.ui.saveButton.clicked.connect(self.save_dataset)
        self.ui.deleteButton.clicked.connect(self.delete_dataset)
        self.ui.newButton.clicked.connect(self.new_dataset)
        self.ui.newFromCopyButton.clicked.connect(self.new_dataset_from_copy)


        self.__initial_form_load__()

    def __check_for_error_on_summing_downloads__(self):
        '''
        Verify if the date formats look like they should be summed
        For summed downloads, the ftp date format does not have to match
        the final date format
        or if summed, curretnly ftp must be day period and final must be
        pentadal or dekadal
        If other combinations are required they need to be added
        '''
        err = False
        final_date_format = self.ui.datadateComboBox.currentText()
        dwnld_date_format = self.ui.uncompdateComboBox.currentText()
        final_date_format_key = None
        dwnld_date_format_key = None
        per_data = None
        per_zip = None
        for key in config.DATE_FORMATS_DIC:
            t_str = config.DATE_FORMATS_DIC[key]['PER_STRING']
            if t_str == final_date_format:
                final_date_format_key = key
            if t_str == dwnld_date_format:
                dwnld_date_format_key = key
        if not final_date_format_key or not dwnld_date_format_key:
            err = True
        else:
            per_data = config.DATE_FORMATS_DIC[
                final_date_format_key]['PERIODICITY']
            per_zip = config.DATE_FORMATS_DIC[
                dwnld_date_format_key]['PERIODICITY']
            # we know we have to sum if the zip periodicity doesn't match the
            # final periodicity
            if per_data != per_zip:
                # currently we only allow daily to sum into dekads or pentads
                # will need to adjust this if other summations are necessary
                if (per_zip == 'Day' and not
                        (per_data in ('Dekadal', 'Pentadal'))):
                    err = True
            else:  # the date formats must be identical or err
                if final_date_format != dwnld_date_format:
                    err = True
        return err

    def __check_new_name__(self, new_name):
        '''
        Check if name exists return err if yes
        :param new_name(string) - New name
        :return err(boolean) - True if name already exists, else False
        '''
        err = False
        dataset_name_list = self.ds_info.get_all_dataset_names()
        if new_name in dataset_name_list or \
                self.ui.datasetComboBox.findText(new_name) != -1:
            err = True
            QMessageBox.critical(
                self, 'Error - Name already exists',
                'The selected name already exists in the database.',
                QMessageBox.Ok)
        return err

    def __check_required_widgets__(self):
        '''
        Check that required widgets are filled.
        :return err(boolean) - True if needed entry is missing, else False
        '''
        form_err = False
        empty_checks = [' ', '']
        req_combo_boxes = [self.ui.datatypeComboBox.currentText(),
                           self.ui.dataextentComboBox.currentText(),
                           self.ui.periodComboBox.currentText(),
                           self.ui.datadateComboBox.currentText(),
                           self.ui.avgComboBox.currentText()]
        req_line_edits = [self.ui.datafolderLineEdit.text(),
                          self.ui.dataprefixLineEdit.text(),
                          self.ui.avgdataLineEdit.text(),
                          self.ui.avgprefixLineEdit.text()]
        check_widgets = req_combo_boxes + req_line_edits
        # verify that all required fields are filled:
        for entry in check_widgets:
            if entry in empty_checks:
                form_err = True
                break
        return form_err

    def __convert_dateformat_widget_val_to_db_string__(self):
        '''
        Convert from what is shown in the gui to what is stored in the db
        for dates formats
        '''
        data_date_format = ''  # Position 6
        file_date_format = ''  # Position 18
        uncompressed_data_date_format = ''  # Position 22
        for key in config.DATE_FORMATS_DIC:
            t_str = config.DATE_FORMATS_DIC[key]['PER_STRING']
            if t_str == self.widget_val_list[6]:
                data_date_format = key
            if t_str == self.widget_val_list[18]:
                file_date_format = key
            if t_str == self.widget_val_list[22]:
                uncompressed_data_date_format = key

        # update the corresponding values in the widget list
        self.widget_val_list[6] = data_date_format
        self.widget_val_list[18] = file_date_format
        self.widget_val_list[22] = uncompressed_data_date_format
        # avgdatadateformat  is at Position 11
        self.widget_val_list[11] =\
            [key for key in config.AVG_DATE_FORMATS_DIC
             if config.AVG_DATE_FORMATS_DIC[key]['PER_STRING'] ==
             self.widget_val_list[11]][0]

    def __convert_datatype_widget_val_to_db_string__(self):
        '''
        Convert from what is shown in the gui to what is stored in the db
        for data types
        '''
        data_type = ''  # Position 1
        for entry in config.DATA_TYPES:
            if entry[0] == self.widget_val_list[1]:
                data_type = entry[1]
        # update the corresponding values in the widget list
        self.widget_val_list[1] = data_type

    def __initial_form_load__(self):
        '''
        Fills the form entries initial load
        '''
        util.fill_misc_widget(self.ui.defaultDSComboBox, ['No', 'Yes'])
        util.fill_misc_widget(
            self.ui.projectionComboBox, config.PROJECTION_LIST)
        util.fill_misc_widget(
            self.ui.avgFileSuffixComboBox, config.VALID_RASTER_SUFFIXES)
        util.fill_misc_widget(
            self.ui.fileSuffixComboBox, config.VALID_RASTER_SUFFIXES)
        util.fill_misc_widget(
            self.ui.uncomprSuffixComboBox, config.VALID_RASTER_SUFFIXES)
        util.fill_misc_widget(
            self.ui.zipSuffixComboBox, config.VALID_ZIP_SUFFIXES)
        for dtype in config.DATA_TYPES:
            self.ui.datatypeComboBox.addItem(dtype[0])

        util.fill_misc_widget(self.ui.dataextentComboBox, config.DATA_EXTENTS)
        util.fill_misc_widget_no_sort(self.ui.periodComboBox,
                                      config.PERIODICITY_LIST)

        util.fill_dataset_combo(self.ui.datasetComboBox)

        ds_dic = self.ds_info.get_ds_dictionary()
        if ds_dic and (ds_dic['FILEDATEFORMAT'] or ds_dic['FILEPREFIX'] or ds_dic['FILESUFFIX']):
            self.ui.lblRemoteDateFormat.show()
            self.ui.ftpfiledateComboBox.show()
            self.ui.lblRemoteFilePrefix.show()
            self.ui.ftpfileprefixLineEdit.show()
            self.ui.lblRemoteFileSuffix.show()
            self.ui.zipSuffixComboBox.show()
            self.ui.isFileCompressedCheckBox.setChecked(True)
        else:
            self.ui.lblRemoteDateFormat.hide()
            self.ui.ftpfiledateComboBox.hide()
            self.ui.lblRemoteFilePrefix.hide()
            self.ui.ftpfileprefixLineEdit.hide()
            self.ui.lblRemoteFileSuffix.hide()
            self.ui.zipSuffixComboBox.hide()
            self.ui.ftpfiledateComboBox.setCurrentIndex(-1)
            self.ui.zipSuffixComboBox.setCurrentIndex(-1)
            self.ui.isFileCompressedCheckBox.setChecked(False)

        self.ui.saveButton.setEnabled(False)

    def __validate_text_inputs__(self):
        '''
        Validate the free form text entries
        return err(boolean) - True if entry has an error, else False
        '''
        err = False
        # these prefix entries must exist
        for entry in [self.ui.dataprefixLineEdit, self.ui.avgprefixLineEdit]:
            err = util.check_line_edit(entry, min_chars=1, max_chars=config.MAX_CHARS)
            if err is True:
                break
        if err is False:
            # these entries are optional, but must check if they exist
            for entry in [self.ui.ftpfileprefixLineEdit,
                          self.ui.uncompprefixLineEdit,
                          self.ui.usernameLineEdit,
                          self.ui.passLineEdit]:
                err = util.check_line_edit(entry, min_chars=0, max_chars=config.MAX_CHARS)
                if err is True:
                    break
        return err

    def browse_avg_path(self):
        '''
        Browse to average data folder.
        '''
        avg_path = QFileDialog.getExistingDirectory(
            self, 'Select Average Data Location', self.data_loc)
        if avg_path:
            self.ui.avgdataLineEdit.setText(
                self.wrksp_setup.fix_os_sep_in_path(avg_path))

    def browse_data_path(self):
        '''
        Browse to data folder.
        '''
        data_path = QFileDialog.getExistingDirectory(
            self, 'Select Data Location', self.data_loc)
        if data_path:
            self.ui.datafolderLineEdit.setText(
                self.wrksp_setup.fix_os_sep_in_path(data_path))

    def delete_dataset(self):
        '''
        Delete selected dataset from the database.
        '''
        ds_name = self.ui.datasetComboBox.currentText()
        reply = QMessageBox.question(
            self,
            'Delete Dataset?',
            'Are you sure you want to delete the ' + ds_name + ' dataset?\n '
            'This cannot be undone.',
            QMessageBox.Yes, QMessageBox.Cancel)

        if reply == QMessageBox.Yes:
            self.ds_info.delete_dataset_record(ds_name)
            # need to fix the combo box
            self.ui.datasetComboBox.removeItem(
                self.ui.datasetComboBox.findText(ds_name))
            # reload the form
            show_dataset = self.ds_info.query_default_dataset_name()
            self.ui.datasetComboBox.setCurrentIndex(
                self.ui.datasetComboBox.findText(show_dataset))

    def get_widget_val_list(self):
        '''
        Get the widget values list
        '''
        return self.widget_val_list

    def match_data_avg_paths(self):
        '''
        Copy data path line edit to average path line edit.
        '''
        self.ui.avgdataLineEdit.setText(self.ui.datafolderLineEdit.text())

    def new_dataset(self):
        '''
        Function to create a new dataset from a reset form.
        '''
        new_dataset_name_dlg = NewNameController('Dataset')
        new_dataset_name_dlg.exec_()
        new_ds_name = new_dataset_name_dlg.get_new_name()

        if new_ds_name:
            err = self.__check_new_name__(new_ds_name)
            if err is False:
                reply = QMessageBox.question(
                    self,
                    'New default dataset?',
                    'Do you want to set this as the default dataset?',
                    QMessageBox.Yes, QMessageBox.No)

                self.ui.datasetComboBox.addItem(new_ds_name)
                self.ui.datasetComboBox.setCurrentIndex(
                    self.ui.datasetComboBox.count() - 1)
                if reply == QMessageBox.Yes:
                    self.ui.defaultDSComboBox.setCurrentIndex(
                        self.ui.defaultDSComboBox.findText('Yes'))
                else:
                    self.ui.defaultDSComboBox.setCurrentIndex(
                        self.ui.defaultDSComboBox.findText('No'))
                self.ui.dataextentComboBox.setCurrentIndex(0)
                self.ui.periodComboBox.setCurrentIndex(0)
                self.ui.datafolderLineEdit.clear()
                self.ui.dataprefixLineEdit.clear()
                self.ui.datadateComboBox.setCurrentIndex(0)
                self.ui.fileSuffixComboBox.setCurrentIndex(0)
                self.ui.missingSpinBox.setValue(
                    config.DEFAULT_NO_DATA)
                self.ui.avgdataLineEdit.clear()
                self.ui.avgprefixLineEdit.clear()
                self.ui.avgComboBox.setCurrentIndex(0)
                self.ui.avgFileSuffixComboBox.setCurrentIndex(0)
                self.ui.avgMissingSpinBox.setValue(
                    config.DEFAULT_NO_DATA)
                self.ui.ftphostLineEdit.clear()
                self.ui.ftpdirLineEdit.clear()
                self.ui.usernameLineEdit.clear()
                self.ui.passLineEdit.clear()
                self.ui.ftpfiledateComboBox.setCurrentIndex(0)
                self.ui.ftpfileprefixLineEdit.clear()
                self.ui.zipSuffixComboBox.setCurrentIndex(0)
                self.ui.uncompdateComboBox.setCurrentIndex(0)
                self.ui.uncompprefixLineEdit.clear()
                self.ui.uncomprSuffixComboBox.setCurrentIndex(0)
                self.ui.scaleFactorSpinBox.setValue(1)

    def new_dataset_from_copy(self):
        '''
        Create a new dataset by copying an existing dataset.
        '''
        new_dataset_name_dlg = NewNameController('Dataset')
        new_dataset_name_dlg.exec_()
        new_ds_name = new_dataset_name_dlg.get_new_name()
        if new_ds_name:
            err = self.__check_new_name__(new_ds_name)
            if err is False:
                reply = QMessageBox.question(
                    self, 'New default dataset?',
                    'Do you want to set this as the default dataset?',
                    QMessageBox.Yes, QMessageBox.No)

                self.ui.datasetComboBox.addItem(new_ds_name)
                self.ui.datasetComboBox.setCurrentIndex(
                    self.ui.datasetComboBox.count() - 1)
                if reply == QMessageBox.Yes:
                    self.ui.defaultDSComboBox.setCurrentIndex(
                        self.ui.defaultDSComboBox.findText('Yes'))
                else:
                    self.ui.defaultDSComboBox.setCurrentIndex(
                        self.ui.defaultDSComboBox.findText('No'))
                self.save_dataset()

    def save_dataset(self):
        '''
        Update dataset database using widget selections.
        '''
        w_err = self.__check_required_widgets__()
        t_err = self.__validate_text_inputs__()
        if self.ui.avgMissingSpinBox.value() != self.ui.missingSpinBox.value():
            self.ui.avgMissingSpinBox.setValue(self.ui.missingSpinBox.value())
            QMessageBox.information(
                self, 'Info - Mis-matched missing values',
                'Data and average missing values must match.\n'
                'Changed average missing value to match data missing value.',
                QMessageBox.Ok)
        if self.ui.avgFileSuffixComboBox.currentText() !=\
                self.ui.fileSuffixComboBox.currentText():
            self.ui.avgFileSuffixComboBox.setCurrentIndex(
                self.ui.avgFileSuffixComboBox.findText(
                    self.ui.fileSuffixComboBox.currentText()))
            QMessageBox.information(
                self, 'Info - Mis-matched suffixes',
                'Data and average suffix must match.\n'
                'Changed average suffix to match data suffix.',
                QMessageBox.Ok)

        # check that date formats match on the ftp side
        if self.ui.isFileCompressedCheckBox.isChecked() and self.ui.ftpfiledateComboBox.currentText() !=\
                self.ui.uncompdateComboBox.currentText():
            QMessageBox.critical(
                self, 'Error - Date format mis-match',
                'Verify that zip and uncompressed date format match.',
                QMessageBox.Ok)
        elif self.__check_for_error_on_summing_downloads__() is True:
            QMessageBox.critical(
                self, 'Error in dataset defintion',
                ("Either the ftp file date formats do not match the final " +
                 "date formats, or the dataset definition is setup for an " +
                 "invalid summation of downloaded files.\n" +
                 "Currently, we only allow daily files to sum into " +
                 "dekadal or pentadal files.\nFor all other downloads, the "
                 "final date format must match the zipped file format.\n" +
                 "Please verify the dataset defintion date formats."),
                QMessageBox.Ok)
        elif w_err is False and t_err is False:
            self.set_widget_val_list()
            self.ds_info.write_dataset_record(self.widget_val_list)
            self.ui.saveButton.setEnabled(False)
        else:
            QMessageBox.critical(
                self, 'Error - Missing information',
                'Required fields are missing or incorrect.\n'
                'Recheck form entries and try again or cancel.',
                QMessageBox.Ok)

    def save_enabled(self):
        '''
        Enable the save button. To save unnecessary writes to the
        database, the button should only be enabled if something has changed
        on the form.
        '''
        self.ui.saveButton.setEnabled(True)

    def update_compression_info(self):
        if self.ui.isFileCompressedCheckBox.isChecked():
            self.ui.lblRemoteDateFormat.show()
            self.ui.ftpfiledateComboBox.show()
            self.ui.lblRemoteFilePrefix.show()
            self.ui.ftpfileprefixLineEdit.show()
            self.ui.lblRemoteFileSuffix.show()
            self.ui.zipSuffixComboBox.show()
        else:
            self.save_enabled()
            self.ui.lblRemoteDateFormat.hide()
            self.ui.ftpfiledateComboBox.hide()
            self.ui.lblRemoteFilePrefix.hide()
            self.ui.ftpfileprefixLineEdit.hide()
            self.ui.lblRemoteFileSuffix.hide()
            self.ui.zipSuffixComboBox.hide()

    def select_periodicity(self):
        '''
        Function to load date format widgets.
        '''
        temp_date_formats = []
        temp_avg_date_formats = []
        all_date_formats = []
        for key in config.DATE_FORMATS_DIC:
            t_str = config.DATE_FORMATS_DIC[key]['PERIODICITY']
            t_str2 = config.DATE_FORMATS_DIC[key]['PER_STRING']
            all_date_formats.append(t_str2)
            if t_str == self.ui.periodComboBox.currentText():
                temp_date_formats.append(t_str2)

        for key in config.AVG_DATE_FORMATS_DIC:
            t_str = config.AVG_DATE_FORMATS_DIC[key]['PERIODICITY']
            t_str2 = config.AVG_DATE_FORMATS_DIC[key]['PER_STRING']
            if t_str == self.ui.periodComboBox.currentText():
                temp_avg_date_formats.append(t_str2)

        # these only load the formats for the dataaset periodicity
        util.fill_misc_widget(self.ui.datadateComboBox, temp_date_formats)
        util.fill_misc_widget(self.ui.avgComboBox, temp_avg_date_formats)
        # these do not have to match the dataset periodicity, load all choices
        util.fill_misc_widget(self.ui.ftpfiledateComboBox, all_date_formats)
        util.fill_misc_widget(self.ui.uncompdateComboBox, all_date_formats)

    def set_widget_val_list(self):
        '''
        Get the widget values into a list
        '''
        ftpfiledate = ''
        compressed_file_prefix = ''
        zipSuffix = ''
        if self.ui.isFileCompressedCheckBox.isChecked():
            ftpfiledate = self.ui.ftpfiledateComboBox.currentText()
            compressed_file_prefix = self.ui.ftpfileprefixLineEdit.text()
            zipSuffix = self.ui.zipSuffixComboBox.currentText()
        self.widget_val_list =\
            [self.ui.datasetComboBox.currentText(),
             self.ui.datatypeComboBox.currentText(),
             self.ui.dataextentComboBox.currentText(),
             self.ui.periodComboBox.currentText(),
             self.ui.datafolderLineEdit.text(),
             self.ui.dataprefixLineEdit.text(),
             self.ui.datadateComboBox.currentText(),
             self.ui.fileSuffixComboBox.currentText(),
             str(self.ui.missingSpinBox.value()),
             self.ui.avgdataLineEdit.text(),
             self.ui.avgprefixLineEdit.text(),
             str(self.ui.avgComboBox.currentText()),
             self.ui.avgFileSuffixComboBox.currentText(),
             str(self.ui.avgMissingSpinBox.value()),
             self.ui.ftphostLineEdit.text(),
             self.ui.ftpdirLineEdit.text(),
             self.ui.usernameLineEdit.text(),
             self.ui.passLineEdit.text(),
             ftpfiledate,
             compressed_file_prefix,
             zipSuffix,
             self.ui.projectionComboBox.currentText(),
             self.ui.uncompdateComboBox.currentText(),
             self.ui.uncompprefixLineEdit.text(),
             self.ui.uncomprSuffixComboBox.currentText(),
             self.ui.defaultDSComboBox.currentText(),
             str(self.ui.scaleFactorSpinBox.value())]
        self.__convert_dateformat_widget_val_to_db_string__()
        self.__convert_datatype_widget_val_to_db_string__()

    def dataset_selection_changed(self):
        '''
        Function to update form widgets when dataset selection changes.
        '''
        # use the name to set ds object data structure vals
        self.ds_info.query_named_dataset(self.ui.datasetComboBox.currentText())
        # get the values for use here
        ds_dic = self.ds_info.get_ds_dictionary()
        # from here must map between dictionary and the widget vals
        for entry2 in config.DATA_TYPES:
            if ds_dic['DATATYPE'] == entry2[1]:
                self.ui.datatypeComboBox.setCurrentIndex(
                    self.ui.datatypeComboBox.findText(entry2[0]))
        if ds_dic['DATAEXTENT']:
            self.ui.dataextentComboBox.setCurrentIndex(
                self.ui.dataextentComboBox.findText(ds_dic['DATAEXTENT']))
        self.ui.periodComboBox.setCurrentIndex(
            self.ui.periodComboBox.findText(ds_dic['PERIODICITY']))
        self.ui.datafolderLineEdit.setText(ds_dic['DATAFOLDER'])
        self.ui.dataprefixLineEdit.setText(ds_dic['DATAPREFIX'])

        for key in config.DATE_FORMATS_DIC:
            t_str = config.DATE_FORMATS_DIC[key]['PER_STRING']
            if ds_dic['DATADATEFORMAT'] == key:
                self.ui.datadateComboBox.setCurrentIndex(
                    self.ui.datadateComboBox.findText(t_str))

        self.ui.fileSuffixComboBox.setCurrentIndex(
            self.ui.fileSuffixComboBox.findText(ds_dic['DATASUFFIX']))
        self.ui.missingSpinBox.setValue(int(ds_dic['DATAMISSINGVALUE']))
        self.ui.avgdataLineEdit.setText(ds_dic['AVGDATAFOLDER'])
        self.ui.avgprefixLineEdit.setText(ds_dic['AVGDATAPREFIX'])
        for key in config.AVG_DATE_FORMATS_DIC:
            t_str = config.AVG_DATE_FORMATS_DIC[key]['PER_STRING']
            if ds_dic['AVGDATADATEFORMAT'] == key:
                self.ui.avgComboBox.setCurrentIndex(
                    self.ui.avgComboBox.findText(t_str))

        self.ui.avgFileSuffixComboBox.setCurrentIndex(
            self.ui.avgFileSuffixComboBox.findText(ds_dic['AVGDATASUFFIX']))
        self.ui.avgMissingSpinBox.setValue(int(ds_dic['AVGDATAMISSINGVALUE']))
        self.ui.ftphostLineEdit.setText(ds_dic['REMOTEHOST'])
        self.ui.ftpdirLineEdit.setText(ds_dic['REMOTEDIRECTORY'])
        self.ui.usernameLineEdit.setText(ds_dic['USERNAME'])
        self.ui.passLineEdit.setText(ds_dic['PASSWORD'])
        for key in config.DATE_FORMATS_DIC:
            t_str = config.DATE_FORMATS_DIC[key]['PER_STRING']
            if ds_dic['FILEDATEFORMAT'] == key:
                self.ui.ftpfiledateComboBox.setCurrentIndex(
                    self.ui.ftpfiledateComboBox.findText(t_str))
            if ds_dic['UNCOMPRESSEDDATADATEFORMAT'] == key:
                self.ui.uncompdateComboBox.setCurrentIndex(
                    self.ui.uncompdateComboBox.findText(t_str))

        self.ui.ftpfileprefixLineEdit.setText(ds_dic['FILEPREFIX'])
        self.ui.zipSuffixComboBox.setCurrentIndex(
            self.ui.zipSuffixComboBox.findText(ds_dic['FILESUFFIX']))
        self.ui.projectionComboBox.findText(
            ds_dic['UNCOMPRESSEDDATAPROJECTION'])
        self.ui.uncompprefixLineEdit.setText(ds_dic['UNCOMPRESSEDDATAPREFIX'])
        self.ui.uncomprSuffixComboBox.setCurrentIndex(
            self.ui.uncomprSuffixComboBox.findText(
                ds_dic['UNCOMPRESSEDDATASUFFIX']))
        self.ui.defaultDSComboBox.setCurrentIndex(
            self.ui.defaultDSComboBox.findText(ds_dic['DEFAULTDS']))
        self.ui.scaleFactorSpinBox.setValue(int(ds_dic['DATASCALEFACTOR']))
        self.ui.saveButton.setEnabled(False)

        if ds_dic and (ds_dic['FILEDATEFORMAT'] or ds_dic['FILEPREFIX'] or ds_dic['FILESUFFIX']):
            self.ui.lblRemoteDateFormat.show()
            self.ui.ftpfiledateComboBox.show()
            self.ui.lblRemoteFilePrefix.show()
            self.ui.ftpfileprefixLineEdit.show()
            self.ui.lblRemoteFileSuffix.show()
            self.ui.zipSuffixComboBox.show()
            self.ui.isFileCompressedCheckBox.setChecked(True)
        else:
            self.ui.lblRemoteDateFormat.hide()
            self.ui.ftpfiledateComboBox.hide()
            self.ui.lblRemoteFilePrefix.hide()
            self.ui.ftpfileprefixLineEdit.hide()
            self.ui.lblRemoteFileSuffix.hide()
            self.ui.zipSuffixComboBox.hide()
            self.ui.ftpfiledateComboBox.setCurrentIndex(-1)
            self.ui.zipSuffixComboBox.setCurrentIndex(-1)
            self.ui.isFileCompressedCheckBox.setChecked(False)
