"""
/***************************************************************************
Name	   :  download_utilities.py
Description:  Download Utility Functions for FEWSTools plugin,
copyright  :  (C) 2022-2023 by FEWS
email      :  minxuansun@contractor.usgs.gov
Created    :  04/08/2022 cholen
Modified   :  07/13/2022 cholen - Update PoolManager call so resource closes.
              09/16/2022 - jhowton - http download error handling

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

/***************************************************************************
 *                                                                         *
 *   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 gzip
import os
import shutil
import tarfile
import time
import urllib3


def download_ftp_file(ftp_obj, dir_path, file_name, dst_folder):
    """
    Function to download a file from url
    params(string) - Download url
    params(string) - Destination folder
    returns(string) - Downloaded file path
    """
    if not os.path.exists(dst_folder):
        os.makedirs(dst_folder)
    dst_file = os.path.join(dst_folder, file_name)
    ftp_obj.retrbinary("RETR " + dir_path + file_name,
                        open(dst_file, "wb").write)
    return dst_file


def download_http_file(url, dst_folder):
    """
    Function to download a file from url
    params(string) - Download url
    params(string) - Destination folder
    returns(string) - Downloaded file path
    """
    if not os.path.exists(dst_folder):
        os.makedirs(dst_folder)
    local_filename = url.split("/")[-1]
    dst_file = os.path.join(dst_folder, local_filename)

    with urllib3.PoolManager() as http:
        with http.request("GET", url, preload_content=False) as resp,\
                open(dst_file, "wb") as dst_file_obj:
            if resp.status == 200:
                shutil.copyfileobj(resp, dst_file_obj)
    return dst_file, resp.status


def get_per_year_from_per_month(interval_dic, period_month_string):
    """
    Gets period of year from period of month.  Used in download data because
    the GUI controls always give the month and period of the month for dekadal
    and pentadal datasets.
    params(dic) -  interval_dic
    params(string) - period_month_string
    return(string) - period_of_year
    """
    period_of_year = None
    for val in interval_dic.values():
        if val["MON_PER"] == period_month_string:
            period_of_year = val["PER_YEAR"]
            break
    return period_of_year


def gunzip(gz_file, dst_file):
    """
    Function to unzip a .gz file
    params(string) - gz filename
    params(string) - Destination file
    """
    # Check to see if the path exists since python's Open() won't
    # create the needed directories.
    if not os.path.exists(os.path.split(dst_file)[0]):
        os.makedirs(os.path.split(dst_file)[0])

    # the "wb" is not working correctly to overwrite the file
    while os.path.exists(dst_file):
        os.remove(dst_file)
        time.sleep(15)
    with gzip.open(gz_file, "rb") as f_in:
        with open(dst_file, "wb") as f_out:
            shutil.copyfileobj(f_in, f_out)


def untar_download(tar_file, dst_path):
    """
    Function to untar file
    params(string) - Tar filename
    params(string) - Destination folder
    """
    with tarfile.open(tar_file, "r") as tar:
        tar.extractall(dst_path)
        