import requests
import time
import pandas as pd
from datetime import date
from datetime import timedelta
import os.path
import csv
import zipfile
import json


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

    base_url = 'https://www.lawa.org.nz/media/5261861/airqualitydownloaddata_2016-2022.xlsx'
    Headers = {'User-Agent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'}

    if mode == 'all':

        os.makedirs('{}/NZ_LAWA/original_files/{}/'.format(dl_root, version), exist_ok=True)
        download_location = '{}/NZ_LAWA/original_files/{}/'.format(dl_root, version)

    elif mode == 'nrt':
        print("No nrt NZ_LAWA")
        exit()

    else:
        print('time mode inapplicable')


    n_tries = 0
    errcode = 999
    while (n_tries < n_max_tries) and (errcode != 200):
        r = requests.get(base_url, timeout=max_time_per_dl, headers=Headers)
        if r.status_code == 200:
            with open(download_location+'data_LAWA.xlsx', 'wb') as file:
                file.write(r.content)

            # convert ot csv
            file = pd.read_excel(download_location+'data_LAWA.xlsx', sheet_name='Air Quality Data')
            file.to_csv(download_location+'data_LAWA.csv', index=None, header=True)

            os.remove(download_location+'data_LAWA.xlsx') # delete excel file
            
            print('Downloaded LAWA')
            errcode = r.status_code

        elif r.status_code == 404:
            print('No LAWA data found')
            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 LAWA data {} times in {} seconds, error code {}'.format(n_tries, max_time_per_dl, errcode))