'''
/***************************************************************************
Name	   :  import_archive_controller.py
Description:  Import archive controller class for FEWSTools plugin,
              updated from QGIS2
copyright  :  (C) 2019-2023 by FEWS
email      :  minxuansun@contractor.usgs.gov
Modified   :  02/10/2020 - cholen - Add in create dataset upon completion and
                                    QMessageBox on invalid import file
              05/01/2020 - cholen - Added more user info to 'completed' dialog
              08/31/2020 - cholen - Include metadata with archive
              10/08/2020 - cholen - Fix os sep in browse
              03/31/2021 - cholen - Add DATASCALEFACTOR handling to
                                    create_new_dataset_from_archive
              02/23/2022 - cholen - Add tiff support
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 QMessageBox, QDialog, QFileDialog

from fews_tools.forms.Ui_ImportArchive import Ui_ImportArchive
from fews_tools.models.datasets_model import DatasetsModel
from fews_tools.models.workspace_setup_model import WorkspaceSetupModel

from fews_tools.utilities import archive_utilities as arc_util
from fews_tools import fews_tools_config as config


class ImportArchiveController(QDialog):
    '''
    Class to handle importing climate data archive files
    '''

    def __init__(self):
        QDialog.__init__(self)
        self.ui = Ui_ImportArchive()
        self.ui.setupUi(self)

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

        self.archive_file = ''
        self.dst_path = self.wrksp_setup.get_climate_data_path()
        self.browse_location = self.wrksp_setup.get_workspace()

        # make connections to methods
        self.ui.browseArchiveButton.clicked.connect(self.browse_archive_path)
        self.ui.browseDestButton.clicked.connect(self.browse_dst_path)
        self.ui.importButton.clicked[bool].connect(self.import_geoclim_archive)

        self.ui.archiveLineEdit.setText(self.archive_file)
        self.ui.dstPathLineEdit.setText(self.dst_path)
        self.ui.archiveLineEdit.setEnabled(False)
        self.ui.dstPathLineEdit.setEnabled(False)
        self.ui.importButton.setEnabled(False)

    def browse_archive_path(self):
        '''
        Function to browse to archive file and set line edit control.
        '''
        file_name =\
            QFileDialog.getOpenFileName(None,
                                        'Select Archive File',
                                        self.browse_location,
                                        '*.climdata ;; *.zip')
        if file_name:
            self.ui.archiveLineEdit.setText(
                self.wrksp_setup.fix_os_sep_in_path(file_name[0]))
            self.ui.importButton.setEnabled(True)
        else:
            self.ui.importButton.setEnabled(False)

    def browse_dst_path(self):
        '''
        Function to browse to destination directory and set line edit control.
        '''
        dir_name =\
            QFileDialog.getExistingDirectory(
                None,
                u'Select location to place dataset folder.',
                self.dst_path)
        if dir_name:
            self.ui.dstPathLineEdit.setText(
                self.wrksp_setup.fix_os_sep_in_path(dir_name))

    def create_new_dataset_from_archive(self, ds_name, def_flag):
        '''
        Creates a new dataset record for an imported archive.
        param(string) - ds_name - Name of the archive(dataset)
        param(boolean) - def_flag - Set as default, True or False
        '''
        # setup a "widget_val_list"
        data_path = os.path.join(self.dst_path, ds_name)
        metadata_file = os.path.join(data_path, arc_util.METADATA_FILENAME)
        temp_ds_dic = arc_util.read_dataset_metadata(metadata_file)
        if temp_ds_dic:
            widget_val_list =\
                [ds_name, temp_ds_dic['DATATYPE'], temp_ds_dic['DATAEXTENT'],
                 temp_ds_dic['PERIODICITY'], data_path,
                 temp_ds_dic['DATAPREFIX'],
                 temp_ds_dic['DATADATEFORMAT'], temp_ds_dic['DATASUFFIX'],
                 temp_ds_dic['DATAMISSINGVALUE'], data_path,
                 temp_ds_dic['AVGDATAPREFIX'],
                 temp_ds_dic['AVGDATADATEFORMAT'],
                 temp_ds_dic['AVGDATASUFFIX'],
                 temp_ds_dic['AVGDATAMISSINGVALUE'],
                 temp_ds_dic['REMOTEHOST'], temp_ds_dic['REMOTEDIRECTORY'],
                 temp_ds_dic['USERNAME'], temp_ds_dic['PASSWORD'],
                 temp_ds_dic['FILEDATEFORMAT'],
                 temp_ds_dic['FILEPREFIX'], temp_ds_dic['FILESUFFIX'],
                 temp_ds_dic['UNCOMPRESSEDDATAPROJECTION'],
                 temp_ds_dic['UNCOMPRESSEDDATADATEFORMAT'],
                 temp_ds_dic['UNCOMPRESSEDDATAPREFIX'],
                 temp_ds_dic['UNCOMPRESSEDDATASUFFIX'],
                 def_flag]
            if 'DATASCALEFACTOR' in temp_ds_dic:
                widget_val_list.append(temp_ds_dic['DATASCALEFACTOR'])
            else:
                widget_val_list.append('1')
        else:
            widget_val_list =\
                [ds_name, 'PPT', 'Global',
                 'Dekadal', data_path, 'data', 'YYYYEK',
                 config.BIL_SUFFIX, config.DEFAULT_NO_DATA,
                 data_path, 'avg', 'EK',
                 config.BIL_SUFFIX, config.DEFAULT_NO_DATA,
                 '', '', '', '', '', '', '', '', '', '', '', def_flag, '1']
        self.ds_info.write_dataset_record(widget_val_list)

    def import_geoclim_archive(self):
        '''
        Import an archive file.  Note that the archive file is required to have
        the extension ".climdata"
        '''
        # lock the gui controls
        self.ui.browseArchiveButton.setEnabled(False)
        self.ui.browseDestButton.setEnabled(False)
        self.ui.importButton.setEnabled(False)
        self.ui.closeButton.setEnabled(False)

        # get a filename for the zipped file
        self.archive_file = self.ui.archiveLineEdit.text()
        self.dst_path = self.ui.dstPathLineEdit.text()
        test_folder_name = os.path.basename(self.archive_file).split('.')[0]
        test_path = os.path.join(self.dst_path, test_folder_name)
        reply = QMessageBox.Yes
        if os.path.exists(test_path):
            reply = QMessageBox.question(self,
                                         u'Folder already exists!',
                                         u'The folder ' + test_path +
                                         ' already exists.\n'
                                         'Do you want to overwrite?',
                                         QMessageBox.Yes, QMessageBox.Cancel)
        err = True
        if reply == QMessageBox.Yes:
            if os.path.exists(self.archive_file) and\
                    os.path.exists(self.dst_path):
                err = arc_util.gc_unzip_file(self, self.archive_file,
                                             self.dst_path)
        if not err:
            reply = QMessageBox.question(self,
                                         u'Import completed!',
                                         u'Import completed.\n\n'
                                         'Do you want to '
                                         'make this new dataset the default?',
                                         QMessageBox.Yes, QMessageBox.No)
            if reply == QMessageBox.Yes:
                def_flag = 'Yes'
            else:
                def_flag = 'No'
            self.create_new_dataset_from_archive(test_folder_name, def_flag)

        # unlock the gui controls
        self.ui.browseArchiveButton.setEnabled(True)
        self.ui.browseDestButton.setEnabled(True)
        self.ui.importButton.setEnabled(True)
        self.ui.closeButton.setEnabled(True)
        self.close()
