#!/usr/bin/env python

# Copyright 2018 Earth Sciences Department, BSC-CNS
#
# This file is part of HERMESv3_GR.
#
# HERMESv3_GR 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 3 of the License, or
# (at your option) any later version.
#
# HERMESv3_GR is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with HERMESv3_GR. If not, see <http://www.gnu.org/licenses/>.


import sys
import os


def query_yes_no(question, default="yes"):
    valid = {"yes": True, "y": True, "1": True, 1: True,
             "no": False, "n": False, "0": False, 0: False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = raw_input().lower()
        if default is not None and choice == '':
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")


def check_args(args, exe_str):
    if len(args) == 0:
        print("Missing destination path after '{0}'. e.g.:".format(exe_str) +
              "\n\t{0} /home/user/HERMES".format(exe_str))
        sys.exit(1)
    elif len(args) > 1:
        print("Too much arguments through '{0}'. Only destination path is needed e.g.:".format(exe_str) +
              "\n\t{0} /home/user/HERMES".format(exe_str))
        sys.exit(1)
    else:
        dir_path = args[0]

    if not os.path.exists(dir_path):
        if query_yes_no("'{0}' does not exist. Do you want to create it? ".format(dir_path)):
            os.makedirs(dir_path)
        else:
            sys.exit(0)

    return dir_path


def download_files(parent_path):
    from ftplib import FTP

    ftp = FTP('bscesftp.bsc.es')
    ftp.login()
    dst_file = os.path.join(parent_path, 'HERMESv3_GR_Benchmark.zip')

    ftp.retrbinary('RETR HERMESv3_GR_Benchmark.zip', open(dst_file, 'wb').write)

    ftp.quit()

    return dst_file


def unzip_files(zippath, parent_path):
    import zipfile

    zip_file = zipfile.ZipFile(zippath, 'r')
    zip_file.extractall(parent_path)
    zip_file.close()
    os.remove(zippath)


def download_benchmark():
    argv = sys.argv[1:]

    parent_dir = check_args(argv, 'hermesv3_gr_download_benchmark')

    zippath = download_files(parent_dir)
    unzip_files(zippath, parent_dir)


if __name__ == '__main__':
    download_benchmark()
