import requests
from datetime import date
import os.path
import time
import json
import csv
import metadata_parsing_functions



def download_data(mode, version, n_max_tries, max_time_per_dl, start, stop, dl_root):

    baseurl = 'https://nadp.slh.wisc.edu/networks/national-trends-network/'

    if mode == 'all':
        os.makedirs('{}/US_NADP_AIRMoN/original_files/{}/'.format(dl_root, version), exist_ok=True)
        download_location = '{}/US_NADP_AIRMoN/original_files/{}/'.format(dl_root,version)

    elif mode == 'nrt':
        os.makedirs('{}/US_NADP_AIRMoN/original_files/nrt/'.format(dl_root), exist_ok=True)
        download_location = '{}/US_NADP_AIRMoN/original_files/nrt/'.format(dl_root)

    else:
        print('time mode inapplicable')

    Headers = {'User-Agent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'}
    url = 'https://nadp.slh.wisc.edu/wp-content/uploads/2021/09/AIRMoN-ALL.csv'
    n_tries = 0
    errcode = 999

    while (n_tries < n_max_tries) and (errcode != 200):
        r = requests.get(url, timeout=max_time_per_dl, headers=Headers)
        if r.status_code == 200:
            with open(download_location+'AIRMoN-ALL.csv', 'wb') as file:
                file.write(r.content)
            print('Downloaded {}'.format(url))
            errcode = r.status_code

        elif r.status_code == 404:
            print('No {}'.format(url))
            errcode = 200 #skip
        else:
            # try again
            print('Response error {}, attempt {}'.format(r.status_code, n_tries))
            errcode = r.status_code
            n_tries += 1
            time.sleep(n_tries ** 2) # wait a lil more every time 

    if n_tries == n_max_tries:
        print('Failed downloading {} {} times in {} seconds, error code {}'.format(url, n_tries, max_time_per_dl, errcode))



def download_metadata(n_max_tries, max_time_per_dl, version, dl_root, meta_basefile,meta_history, meta_params):

    os.makedirs('{}/US_NADP_AIRMoN/metadata/{}/network_provided/'.format(dl_root,version), exist_ok=True)
    os.makedirs('{}/US_NADP_AIRMoN/metadata/{}/processed/'.format(dl_root,version), exist_ok=True)

    download_location = '{}/US_NADP_AIRMoN/metadata/{}/network_provided/'.format(dl_root, version)
    today = date.today()

    Headers = {'User-Agent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'}
    url = 'https://nadp.slh.wisc.edu/wp-content/uploads/2021/09/AIRMoNsites.csv'
    n_tries = 0
    errcode = 999

    while (n_tries < n_max_tries) and (errcode != 200):
        r = requests.get(url, timeout=max_time_per_dl, headers=Headers)
        if r.status_code == 200:
            with open(download_location+'US_NADP_AIRMoN_META_{}.csv'.format(today.strftime('%Y%m%d')), 'wb') as file:
                file.write(r.content)
            print('Downloaded {}'.format(url))
            errcode = r.status_code

        elif r.status_code == 404:
            print('No {}'.format(url))
            errcode = 200 #skip
        else:
            # try again
            print('Response error {}, attempt {}'.format(r.status_code, n_tries))
            errcode = r.status_code
            n_tries += 1
            time.sleep(n_tries ** 2) # wait a lil more every time 

    if n_tries == n_max_tries:
        print('Failed downloading {} {} times in {} seconds, error code {}'.format(url, n_tries, max_time_per_dl, errcode))


    # JSON =====================================================================
    network = os.path.basename(__file__).split('_downloa')[0]
    present_meta_file_id = today.strftime('%Y%m%d')

    metadata_parsing_functions.json_parser(dl_root, network, version, meta_basefile, meta_history, meta_params, present_meta_file_id)
