"""Create an analysis of LSR snowfall reports"""
import numpy as np
from pyiem.plot import MapPlot
import pyiem.reference as reference
import datetime
import unittest
import psycopg2
import pandas as pd
from pandas.io.sql import read_sql
POSTGIS = psycopg2.connect(database='postgis', host='iemdb', user='nobody')


def run(basets, endts, view):
    """Generate this plot for the given basets"""

    df = read_sql("""SELECT state,
        max(magnitude) as val, ST_x(geom) as lon, ST_y(geom) as lat
        from lsrs WHERE type in ('S') and magnitude >= 0 and
        valid > %s and valid < %s GROUP by state, lon, lat
        """, POSTGIS, params=(basets, endts), index_col=None)
    df['used'] = False
    df['textplot'] = True
    df.sort_values(by='val', ascending=False, inplace=True)

    # Now, we need to add in zeros, lets say we are looking at a .25 degree box
    mybuffer = 0.75
    newrows = []
    for lat in np.arange(reference.MW_SOUTH, reference.MW_NORTH, mybuffer):
        for lon in np.arange(reference.MW_WEST, reference.MW_EAST, mybuffer):
            df2 = df[(df['lat'] >= lat) & (df['lat'] < (lat+mybuffer)) &
                     (df['lon'] >= lon) & (df['lon'] < (lon+mybuffer))]
            if len(df2.index) == 0:
                newrows.append(dict(lon=(lon+mybuffer/2.),
                                    lat=(lat+mybuffer/2.),
                                    val=0, used=True, textplot=False))
                continue
            maxval = df.at[df2.index[0], 'val']
            df.loc[df2[df2['val'] > (maxval * 0.5)].index, 'used'] = True
            df.loc[df2[df2['val'] < (maxval * 0.5)].index, 'textplot'] = False
    dfnew = pd.DataFrame(newrows)
    df = df.append(dfnew)
    cdf = df[df['used']]
    tdf = df[df['textplot']]

    rng = [0.01, 0.1, 0.25, 0.5, 1, 2, 3, 5, 7, 9, 11, 13, 15, 17]

    m = MapPlot(sector='iowa', axisbg='white',
                title="Local Storm Report Snowfall Total Analysis",
                subtitle=("Reports past 12 hours: %s"
                          "" % (endts.strftime("%d %b %Y %I:%M %p"), )))
    m.contourf(cdf['lon'].values, cdf['lat'].values, cdf['val'].values, rng)
    m.drawcounties()
    m.plot_values(tdf['lon'].values, tdf['lat'].values, tdf['val'].values,
                  fmt='%.1f')
    pqstr = "plot c 000000000000 lsr_snowfall.png bogus png"
    m.postprocess(view=view, pqstr=pqstr)
    m.close()

    # slightly different title to help uniqueness
    m = MapPlot(sector='iowa', axisbg='white',
                title="Local Storm Report Snowfall Total Analysis",
                subtitle=("Reports valid over past 12 hours: %s"
                          "" % (endts.strftime("%d %b %Y %I:%M %p"), )))
    m.contourf(cdf['lon'].values, cdf['lat'].values, cdf['val'].values, rng)
    m.drawcounties()
    pqstr = "plot c 000000000000 lsr_snowfall_nv.png bogus png"
    m.postprocess(view=view, pqstr=pqstr)
    m.close()

    m = MapPlot(sector='midwest', axisbg='white',
                title="Local Storm Report Snowfall Total Analysis",
                subtitle=("Reports past 12 hours: %s"
                          "" % (endts.strftime("%d %b %Y %I:%M %p"), )))
    m.contourf(cdf['lon'].values, cdf['lat'].values, cdf['val'].values, rng)
    pqstr = "plot c 000000000000 mw_lsr_snowfall.png bogus png"
    m.postprocess(view=view, pqstr=pqstr)
    m.close()


def main():
    """Do Something"""
    now = datetime.datetime.now()
    ts = now - datetime.timedelta(hours=12)
    run(ts, now, False)

if __name__ == '__main__':
    main()


class PlotTest(unittest.TestCase):

    def test_plot(self):
        """ Test a plot"""
        run(datetime.datetime(2015, 2, 1, 0),
            datetime.datetime(2015, 2, 2, 12), True)

@@ -91,16 +91,25 @@
  MapPlot
+, nwssnow
 %0Aimport 
@@ -1796,24 +1796,8 @@
 .01,
- 0.1, 0.25, 0.5,
  1, 
@@ -1806,33 +1806,57 @@
  3, 
-5, 7, 9, 11, 13, 15, 17%5D%0A
+4, 6, 8, 12, 18, 24, 30, 36%5D%0A    cmap = nwssnow()
 %0A   
@@ -2161,32 +2161,58 @@
 al'%5D.values, rng
+,%0A               cmap=cmap
 )%0A    m.drawcoun
@@ -2815,24 +2815,50 @@
 .values, rng
+,%0A               cmap=cmap
 )%0A    m.draw
@@ -3226,32 +3226,32 @@
 %25I:%25M %25p%22), )))%0A
-
     m.contourf(c
@@ -3309,16 +3309,42 @@
 ues, rng
+,%0A               cmap=cmap
 )%0A    pq

use new NWS Color ramp for LSR snowfall mapping