#!/usr/bin/env python 
'''Create magnetic declination table from UTM coordinates in degrees
Requires `pip install docopt numpy utm`

Usage:
    makedeclinationtable.py <easting> <northing> <zone> <letter>

Arguments:
    easting   UTM Easting of the site
    northing  UTM Northing of the site
    zone      UTM zone
    letter    UTM letter
'''
from docopt import docopt
import requests
import json
import utm

#convert date to timestamp (float). 
#Taken from https://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python

from datetime import datetime, date, timezone
import calendar
def gettimestamp(year, month, day):
    d = date(year, month, day)
    ts = calendar.timegm(d.timetuple())
    dt = datetime.utcfromtimestamp(ts)
    fts = dt.replace(tzinfo=timezone.utc).timestamp()
    return int(fts)

args = docopt(__doc__, version='0.1')
easting =  args['<easting>'] 
northing = args['<northing>']  
zone = args['<zone>']
letter = args['<letter>']
latitude, longitude = utm.to_latlon(float(easting), float(northing), int(zone), letter)
print("#lat long",latitude,longitude)
    
model = 'IGRF' #data for 1590-2024
day = 1

for year in range(2000,2025,1):
    for month in range(1,13,1):
        x = requests.get('https://www.ngdc.noaa.gov/geomag-web/calculators/calculateDeclination?lat1='+str(latitude) + \
                '&lon1='+str(longitude) + \
                '&model='+model +  \
                '&startYear='+str(year) + \
                '&startMonth='+str(month) + \
                '&startDay='+str(day) + \
                '&resultFormat=json')
        y = json.loads(x.text)
        result = y['result'][0]
        declination = result['declination']
        print(gettimestamp(year,month, day), declination)