from datetime import datetime, timedelta
from urllib import urlretrieve
import sys
import os


# a pattern for a link to the two files for northern and southern 
# hemisphere respectively
url_pattern = 'ftp://osisaf.met.no/prod/ice/conc/ice_conc_{0}_polstere-100_multi_{1}1200.nc'
# we always download the product with yesterday as reference time
yesterday = datetime.now() - timedelta(days=1)
yesterday_str = datetime.strftime(yesterday, '%Y%m%d')


def report_hook(count, block_size, total_size):
    # this function is just a progress indicator for the downloads
    size_mb = total_size / 1024.0 ** 2
    downloaded = min(100, float(count * block_size) / total_size * 100)
    msg = '\rDownloaded % 3.1f%% of %d MB'
    sys.stdout.write(msg % (downloaded, size_mb))
    sys.stdout.flush()

# local_data will hold the files that we downloaded per hemisphere
local_data = {}
for hemis in ['nh', 'sh']:
    url = url_pattern.format(hemis, yesterday_str)
    local_file = os.path.join('/tmp', os.path.basename(url))
    if not os.path.isfile(local_file):
        urlretrieve(url, filename=local_file, reporthook=report_hook)
    local_data[hemis] = local_file

"""
Explanation: Data Retrival
First we need some geolocated data to plot. For this example we use the OSI SAF ice concentration product (http://osisaf.met.no), NetCDF files, which hold ice concentration percentages ranging from zero (= open water) to 100 (= densily packed ice) on a ten-by-ten kilometer grid for the Arctic and the Antarctic.
End of explanation
"""


%load_ext autoreload
%autoreload 2

from netCDF4 import Dataset
from globeplot.plotting import GlobePlot

# read the data and latitudes and longitudes from the northern hemisphere
ds_nh = Dataset(local_data['nh'])
lat_nh = ds_nh.variables['lat'][:]
lon_nh = ds_nh.variables['lon'][:]
values_nh = ds_nh.variables['ice_conc'][0][:]

# read the data and latitudes and longitudes from the southern hemisphere
ds_sh = Dataset(local_data['sh'])
lat_sh = ds_sh.variables['lat'][:]
lon_sh = ds_sh.variables['lon'][:]
values_sh = ds_sh.variables['ice_conc'][0][:]

# reduce the amount of data by not plotting open water (value 0)
plot = GlobePlot(lats=lat_nh[values_nh > 0], lons=lon_nh[values_nh > 0], 
                 data=values_nh[values_nh > 0])

# append the reduced data for the southern hemisphere to the plot
plot.append(lat_sh[values_sh > 0], lon_sh[values_sh > 0], values_sh[values_sh > 0])

"""
Explanation: Data Reading and Plot Instantiation
After downloading the files to a local temporary directory, we read both files and generate a plot instance.
End of explanation
"""


# the following information will be displayed in the plot
yesterday_str = datetime.strftime(yesterday, '%Y-%m-%d')
title = 'OSI SAF Ice Concentration {}'.format(yesterday_str)
source = 'ftp://osisaf.met.no'
link = 'https://github.com/HelgeDMI/trollplot'

plot.show(title=title, creator='Helge', creator_addr=source, code_link=link)

"""
Explanation: Show the Plots...
Finally show the plot in a new tab.
End of explanation
"""


plot.display(title=title, creator='Helge', creator_addr=source, code_link=link)

"""
Explanation: Alternatively, display the plot inlined in a notebook.
End of explanation
"""


