'''
/***************************************************************************
Name	   :  archive_utilities.py
Description:  GeoCLIM Archive Utility Functions for FEWSTools plugin
copyright  :  (C) 2020 - 2023 by FEWS
email      :  minxuansun@contractor.usgs.gov
Created    :  08/31/2020 cholen
Modified   :  xx/xx/xxxx <developer> - Mod
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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
import tarfile


from PyQt5.QtWidgets import QMessageBox

from fews_tools import fews_tools_config as config

METADATA_FILENAME = '_dataset'


def gc_unzip_file(qdialog, tgz_file, dst_dir):
    '''
    Unzip a file into a specified directory. The basename of the tgz_file
    will be used to create a folder in the dst_dir, into which the files
    will unzip.
    :param(Qdialog) - A Qdialog object. The reason we need it is because we
    need Qt.WindowStaysOnTopHint flag from the Qdialog. And QMessageBox can be
    showed on top.
    param(string) - tgz_file - Zipped filename.
    param(string) - dst_dir - The directory where the unzipped folder will be
                              placed.
    return(boolean) - err_val - True if error else False
    '''
    err_val = True
    try:
        with tarfile.open(tgz_file, 'r:gz') as tar:
            tar.extractall(dst_dir)
            err_val = False
    except tarfile.ReadError as err:
        QMessageBox.critical(
            qdialog, str(err),
            (u'The file you selected is not recognized as a '
             'valid gzip file.\nFor QGIS3, the archive files must '
             'be created with Python3.\nPlease select a valid file.'),
            QMessageBox.Ok)
    except OSError as err:
        QMessageBox.critical(
            qdialog, str(err),
            (u'The file you selected is not recognized as a '
             'valid gzip file.\nFor QGIS3, the archive files must '
             'be created with Python3.\nPlease select a valid file.'),
            QMessageBox.Ok)
    return err_val


def gc_zip_file(tgz_file, src_dir):
    '''
    Zip the files in the fileList.
    param(string) - tgz_file - Zipped filename.
    param(string) - src_dir - The directory to zip.
    '''
    with tarfile.open(tgz_file, 'w:gz') as tar:
        tar.add(src_dir, arcname=os.path.basename(src_dir))


def read_dataset_metadata(metadata_filename):
    '''
    Read a metadata file to fill in dataset definition
    param(string) - metadata_filename
    returns(dic) - ds_dic
    '''
    ds_dic = {
        'DATATYPE': '',
        'DATAEXTENT': '',
        'PERIODICITY': '',
        'DATAPREFIX': '',
        'DATADATEFORMAT': '',
        'DATASUFFIX': '',
        'DATAMISSINGVALUE': '',
        'AVGDATAPREFIX': '',
        'AVGDATADATEFORMAT': '',
        'AVGDATASUFFIX': '',
        'AVGDATAMISSINGVALUE': '',
        'REMOTEHOST': '',
        'REMOTEDIRECTORY': '',
        'USERNAME': '',
        'PASSWORD': '',
        'FILEDATEFORMAT': '',
        'FILEPREFIX': '',
        'FILESUFFIX': '',
        'UNCOMPRESSEDDATAPROJECTION': '',
        'UNCOMPRESSEDDATADATEFORMAT': '',
        'UNCOMPRESSEDDATAPREFIX': '',
        'UNCOMPRESSEDDATASUFFIX': ''}

    if os.path.exists(metadata_filename):
        # read the information from file
        with open(metadata_filename, 'r') as read_obj:
            for row in read_obj:
                temp_string = row.strip()
                if ' ' in temp_string:
                    elem, elem_val = temp_string.split(' ')
                    if elem in ds_dic.keys():
                        ds_dic[elem] = str(elem_val)
    return ds_dic


def write_dataset_metadata(ds_dic, archive_name):
    '''
    Write a metadata file from a dataset definition
    param(dic) - The dataset dictionary
    param(string) - Archive name
    '''
    m_file = os.path.join(ds_dic['DATAFOLDER'], METADATA_FILENAME)
    with open(m_file, 'w') as metadata_file:
        metadata_file.write('BEGIN DATASET' + config.CR)
        metadata_file.write('\tDATASETNAME ' + archive_name + config.CR)
        for key, val in ds_dic.items():
            if key not in ['DATASETNAME', 'DEFAULTDS']:
                if 'FOLDER' in key:
                    metadata_file.write('\t' + key + ' ' +
                                        archive_name + config.CR)
                else:
                    metadata_file.write('\t' + key + ' ' +
                                        str(val) + config.CR)
        metadata_file.write('END DATASET ' + config.CR)
