"""get_ww3.py
Download records from WaveWatch III (WW3) global wave model.
D. Howe
2019-07-31
"""
import netCDF4
import pandas as pd
import xarray as xr
from tqdm import tqdm

# Set coordinates
lon = 136.62
lat = -36.07

# Set product code
product_code = 'ww3.aus_4m'

# Select output variables
var_names = ['hs', 'dp', 'fp']

# Set time period
start_date = '1980-01'
end_date = '1980-12'

url = ('http://data-cbr.csiro.au/thredds/dodsC/catch_all/'
       'CMAR_CAWCR-Wave_archive/CAWCR_Wave_Hindcast_aggregate/gridded/')

# Generate list of dates
t0 = pd.to_datetime(start_date)
t1 = pd.to_datetime(end_date) + pd.DateOffset(months=1)
dates = pd.date_range(t0, t1, freq='M')

# Create output dataframe
master = pd.DataFrame()

for date in tqdm(dates):
    # Get date string for current month
    date_str = date.strftime('%Y%m')

    # Open dataset
    ds = xr.open_dataset(url + f'{product_code}.{date_str}.nc')

    # Extract variables from dataset
    ds = ds.sel(longitude=lon, latitude=lat, method='nearest')
    df = ds[var_names].to_dataframe()

    # Add to output dataframe
    master = master.append(df)

# Get lat and lon bearings
ew = 'E' if lon > 0 else 'W'
ns = 'N' if lat > 0 else 'S'

# Export to csv
csv_name = f'{product_code}_{abs(lon)}{ew}_{abs(lat)}{ns}.csv'
master.to_csv(csv_name)
