#! /usr/bin/env python3

"""\
"""

from __future__ import print_function
from datetime import datetime, timedelta

from subprocess import Popen

import argparse
import getpass
import os
import sys
import textwrap

import six



def parse_coord(s):
    try:
        return "%02d" % int(s)
    except ValueError:
        return s


def parse_date(s):
    if len(s) == 10:
        return datetime.strptime(s, '%Y-%m-%d')
    else:
        return datetime.strptime(s, '%Y-%j')



def iter_dates(start, stop):
    current = start
    while current <= stop:
        yield current
        current += timedelta(days=1)


def download(product, start, stop, folder, h='??', v='??',
        user=None, pwd=None, root='.'):

    # username and password
    if user is None:
        user = input('User: ')
    if pwd is None:
        pwd = getpass.getpass('Password: ')

    for date in iter_dates(start, stop):

        print(date.strftime('%Y-%m-%d'))

        date = date.strftime('%Y.%m.%d')
        command = ' '.join([
            'wget', '-q', '-r', '-l1', '-nd', '-nc', '--no-parent',
            '--user=%s' % user, '--password=%s' % pwd,
            '--directory-prefix=%s' % os.path.join(root, product),
            '-A', '"*.h%sv%s.*.hdf"' % (h,v),
            '"https://e4ftl01.cr.usgs.gov/%s/%s/%s/"' % (folder, product, date)
        ])
        os.system(command)


def main():
    #start = datetime.strptime(sys.argv[1], '%Y-%m-%d')
    #stop = datetime.strptime(sys.argv[2], '%Y-%m-%d')

    #product = 'MOD09A1.006'
    #folder = 'MOLT'

    product = 'MCD43A3.006'
    folder = 'MOTA'

    root = '/input/MODIS/'

    description = textwrap.dedent("""\

        Python script for downloading MODIS data from 'https://e4ftl01.cr.usgs.gov'

        Author: Gerrit Kuhlmann
        Email: gerrit.kuhlmann@empa.ch

        Downloading MODIS data requires a NASA Earthdata Login username & password.
        To obtain an account, visit 'https://urs.earthdata.nasa.gov/users/new/'

    """)


    parser = argparse.ArgumentParser(description=description, epilog='',
            formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('starttime', type=str, help='start date (YYYY-mm-dd or YYYY-jjj)')
    parser.add_argument('stoptime', type=str, help='stop date (YYYY-mm-dd or YYYY-jjj)')

    parser.add_argument('h', metavar='horizontal', default='??', type=str,
            help='horizontal tile coordinate [0..35]')
    parser.add_argument('v', metavar='vertical', default='??', type=str,
            help='vertical tile coordinate [0..17]')


    parser.add_argument('--product', default=product, type=str,
            help='name of MODIS product (default: "%(default)s")')

    parser.add_argument('--username', default=None, type=str, help='user name for NASA Earthdata Login')
    parser.add_argument('--password', default=None, type=str, help='password for NASA Earthdata Login')

    parser.add_argument('--prefix', default='.', type=str, help='root folder')


    args = parser.parse_args()


    start = parse_date(args.starttime)
    stop = parse_date(args.stoptime)


    h = parse_coord(args.h)
    v = parse_coord(args.v)

    download(args.product, start, stop, folder, h, v, root='.')


if __name__ == '__main__':
    main()


