import pyart
from matplotlib import pyplot as plt
import numpy as np
import os
import s3fs
from datetime import datetime as dt

%matplotlib inline
print(pyart.__version__)

import warnings
warnings.simplefilter("ignore", category=DeprecationWarning)
#warnings.simplefilter('ignore')

def get_latest_file(radar_id, bucket='noaa-nexrad-level2', engine='s3fs'):
    """Return latest NEXRAD data file name."""
    s3conn = s3fs.S3FileSystem(anon=True)
    latest_year = os.path.join(
        bucket, os.path.basename(s3conn.ls(bucket)[-1]))
    latest_month = os.path.join(
        latest_year, os.path.basename(s3conn.ls(latest_year)[-1]))
    latest_day = os.path.join(
        latest_month, os.path.basename(s3conn.ls(latest_month)[-1]))
    return s3conn.ls(os.path.join(latest_day, radar_id))[-1]

"""
Explanation: Visualizations with Py-ART
First we'll import needed packages
End of explanation
"""


cm_names = pyart.graph.cm._cmapnames
cms = pyart.graph.cm.cmap_d

nrows = len(cm_names)
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))

# Create a figure and axes instance
fig, axes = plt.subplots(nrows=nrows, figsize=(5,10))
fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)
axes[0].set_title('Py-Art Colormaps', fontsize=14)

# Loop through the possibilities
for nn, pymap in enumerate(cm_names):
    axes[nn].imshow(gradient, aspect='auto', cmap=cms[pymap])
    pos = list(axes[nn].get_position().bounds)
    x_text = pos[0] - 0.01
    y_text = pos[1] + pos[3]/2.
    fig.text(x_text, y_text, pymap, va='center', ha='right', fontsize=8)

# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axes:
    ax.set_axis_off()

"""
Explanation: Py-ART Colormaps
Retrieve the names of colormaps and the colormap list dictionary.
The colormaps are registered with matplotlib and can be accessed by inserting 'pyart_' in front of any name.
End of explanation
"""


### Plot a NEXRAD file

nexf = "data/KILN20140429_231254_V06"
nexr = pyart.io.read(nexf)
nexd = pyart.graph.RadarDisplay(nexr)

nexr.fields.keys()

fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(16, 12))
nexd.plot('reflectivity', sweep=1, cmap='pyart_NWSRef', vmin=0., vmax=55., mask_outside=False, ax=ax[0, 0])
nexd.plot_range_rings([50, 100], ax=ax[0, 0])
nexd.set_limits((-150., 150.), (-150., 150.), ax=ax[0, 0])

nexd.plot('velocity', sweep=1, cmap='pyart_NWSVel', vmin=-30, vmax=30., mask_outside=False, ax=ax[0, 1])
nexd.plot_range_rings([50, 100], ax=ax[0, 1])
nexd.set_limits((-150., 150.), (-150., 150.), ax=ax[0, 1])

nexd.plot('cross_correlation_ratio', sweep=0, cmap='pyart_BrBu12', vmin=0.85, vmax=1., mask_outside=False, ax=ax[1, 0])
nexd.plot_range_rings([50, 100], ax=ax[0, 1])
nexd.set_limits((-150., 150.), (-150., 150.), ax=ax[0, 1])

nexd.plot('differential_reflectivity', sweep=0, cmap='pyart_BuDOr12', vmin=-2, vmax=2., mask_outside=False, ax=ax[1, 1])
nexd.plot_range_rings([50, 100], ax=ax[1, 1])
nexd.set_limits((-150., 150.), (-150., 150.), ax=ax[1, 1])

"""
Explanation: The RadarDisplay
This is the most commonly used class designed for surface-based scanning radar
End of explanation
"""


nexd.plot_azimuth_to_rhi('reflectivity', 305., cmap='pyart_NWSRef', vmin=0., vmax=55.)
nexd.set_limits((0., 150.), (0., 15.))

"""
Explanation: There are many keyword values we can employe to refine the plot
Keywords exist for title, labels, colorbar, along with others.
In addition, there are many methods that can be employed. For example, pull out a constructed RHI at a given azimuth.
End of explanation
"""


rhif = "data/noxp_rhi_140610232635.RAWHJFH"
rhir = pyart.io.read(rhif)
rhid = pyart.graph.RadarDisplay(rhir)

rhid.plot_rhi('reflectivity', 0, vmin=-5.0, vmax=70,)

"""
Explanation: Py-ART RHI
Not only can we construct an RHI from a PPI volume, but RHI scans may be plotted as well.
End of explanation
"""


nexmap = pyart.graph.RadarMapDisplayCartopy(nexr)

fig, ax = plt.subplots(1, 1, figsize=(7, 7))
nexmap.plot_ppi_map('reflectivity', sweep=1, vmin=0., vmax=55., ax=ax)
nexmap.ax.set_extent([-87., -82., 37., 42.])

"""
Explanation: Py-ART RadarMapDisplay or RadarMapDisplayCartopy
This converts the x-y coordinates to latitude and longitude overplotting on a map
End of explanation
"""


# %load solution.py

"""
Explanation: Use what you have learned!
Using all that you have learned, make a two panel plot of reflectivity and doppler velocity using the data file from an RHI of NOXP data/noxp_rhi_140610232635.RAWHJFH. Use Cartopy to overlay the plots on a map of Austrailia and play around with differing colormaps and axes limits! 
Solution
The following cell loads a solution to the above problem.
End of explanation
"""


