#!/usr/bin/env python
""" JSON service providing IEMRE data for a given point """

import sys
import os
import cgi
from pyiem import iemre, datatypes
import netCDF4
import datetime
import json
import numpy as np


def myrounder(val, precision):
    """round a float or give back None"""
    if val is None or np.isnan(val) or np.ma.is_masked(val):
        return None
    return round(val, precision)


def main():
    """Do Something Fun!"""
    form = cgi.FormContent()
    ts = datetime.datetime.strptime(form["date"][0], "%Y-%m-%d")
    lat = float(form["lat"][0])
    lon = float(form["lon"][0])
    fmt = form["format"][0]
    if fmt != 'json':
        sys.stdout.write("Content-type: text/plain\n\n")
        sys.stdout.write("ERROR: Service only emits json at this time")
        return

    i, j = iemre.find_ij(lon, lat)
    offset = iemre.daily_offset(ts)

    res = {'data': [], }

    fn = "/mesonet/data/iemre/%s_mw_daily.nc" % (ts.year,)

    sys.stdout.write('Content-type: application/json\n\n')
    if not os.path.isfile(fn):
        sys.stdout.write(json.dumps(res))
        sys.exit()

    if i is None or j is None:
        sys.stdout.write(json.dumps({'error': 'Coordinates outside of domain'}
                                    ))
        return

    nc = netCDF4.Dataset(fn, 'r')

    c2000 = ts.replace(year=2000)
    coffset = iemre.daily_offset(c2000)

    cnc = netCDF4.Dataset("/mesonet/data/iemre/mw_dailyc.nc", 'r')

    res['data'].append({
        'daily_high_f': myrounder(
           datatypes.temperature(
                nc.variables['high_tmpk'][offset, j, i], 'K').value('F'), 1),
        'climate_daily_high_f': myrounder(
           datatypes.temperature(
                cnc.variables['high_tmpk'][coffset, j, i], 'K').value("F"), 1),
        'daily_low_f': myrounder(
           datatypes.temperature(
                nc.variables['low_tmpk'][offset, j, i], 'K').value("F"), 1),
        'climate_daily_low_f': myrounder(
           datatypes.temperature(
                cnc.variables['low_tmpk'][coffset, j, i], 'K').value("F"), 1),
        'daily_precip_in': myrounder(
           nc.variables['p01d'][offset, j, i] / 25.4, 2),
        'climate_daily_precip_in': myrounder(
           cnc.variables['p01d'][coffset, j, i] / 25.4, 2),
      })
    nc.close()
    cnc.close()

    sys.stdout.write(json.dumps(res))

if __name__ == '__main__':
    main()

@@ -1610,24 +1610,189 @@
 e('F'), 1),%0A
+        '12z_high_f': myrounder(%0A           datatypes.temperature(%0A                nc.variables%5B'high_tmpk_12z'%5D%5Boffset, j, i%5D,%0A                'K').value('F'), 1),%0A
         'cli
@@ -1814,32 +1814,32 @@
 _f': myrounder(%0A
-
            datat
@@ -2073,32 +2073,195 @@
 value(%22F%22), 1),%0A
+        '12z_low_f': myrounder(%0A           datatypes.temperature(%0A                nc.variables%5B'low_tmpk_12z'%5D%5Boffset, j, i%5D,%0A                'K').value('F'), 1),%0A
         'climate
@@ -2429,32 +2429,32 @@
 in': myrounder(%0A
-
            nc.va
@@ -2491,24 +2491,122 @@
 / 25.4, 2),%0A
+        '12z_precip_in': myrounder(%0A           nc.variables%5B'p01d_12z'%5D%5Boffset, j, i%5D / 25.4, 2),%0A
         'cli

add 12z high,low,precip var to IEMRE daily JSON service