""".. title:: SchoolNet Hourly Precipitation Grid

Very much legacy stuff.

"""

from datetime import datetime, timedelta
from io import StringIO

from pyiem.database import get_dbconnc
from pyiem.network import Table as NetworkTable
from pyiem.webutil import iemapp

nt = NetworkTable(["KCCI", "KIMIT", "KELO"], only_online=False)

requireHrs = [0] * 25
stData = {}
totp = {}


# Return the Date we will be looking for...
def doHeader(environ, start_response, sio):
    """header please"""
    start_response("200 OK", [("Content-type", "text/html")])
    sio.write(
        """
<html>
<head>
  <title>IEM | Hourly Precip Grid</title>
</head>
<body bgcolor="white">
<a href="/index.php">Iowa Mesonet</a> &gt;
<a href="/schoolnet/">School Net</a> &gt;
Hourly Precipitation [SNET]
<br>This archive starts on 12 Feb 2002 for KCCI sites and 12 Sept 2002 for
KELO sites. SchoolNet data stops on 3 May 2019.

"""
    )
    sio.write('<h3 align="center">Hourly Precip Grid</h3>')
    try:
        postDate = environ.get("date")
        myTime = datetime.strptime(postDate, "%Y-%m-%d")
    except Exception:
        myTime = datetime(2019, 5, 3)

    sio.write("<table border=1><tr>")
    sio.write(
        '<td>Back: <a href="catSNET.py?date='
        + (myTime - timedelta(days=1)).strftime("%Y-%m-%d")
        + '"> \
        '
        + (myTime - timedelta(days=1)).strftime("%Y-%m-%d")
        + "</a></td>"
    )

    sio.write("<td>Shown: " + myTime.strftime("%d %B %Y") + "</td>")

    sio.write(
        '<td>Forward: <a href="catSNET.py?date='
        + (myTime + timedelta(days=1)).strftime("%Y-%m-%d")
        + '"> \
        '
        + (myTime + timedelta(days=1)).strftime("%Y-%m-%d")
        + "</a></td>"
    )

    sio.write(
        """
<td>Pick: (yyyy-mm-dd)
<form method="GET" action="catSNET.py">
<input type="text" size="8" name="date">
<input type="submit" value="Submit Date">
</form></td></tr></table>
"""
    )
    return myTime


def setupTable(sio):
    """Do"""
    sio.write(
        """
<style language="css">
td.style1{
  background-color: #EEEEEE;
}
td.style2{
  background-color: #ffefe1;
}
td.style0{
  background-color: #c6e3ff;
}
tr.row1{
  border-bottom: 4pt;
  border-top: 4pt;
  border-right: 4pt;
  border-left: 4pt;
  background-color: #dddddd;
}
table.main{
  font-size: 8pt;
  font-face: arial sans-serif;
}
</style>
<table width="100%" class="main">
<tr>
  <th rowspan="2">Station</th>
  <th colspan="11">Morning (AM)</th>
  <td></td>
  <th colspan="12">Afternoon/Evening (PM)</th>
  <td></td>
   <th rowspan="2">Station</th>
</tr>
<tr>
  <td class="style0">Mid</td>
  <td class="style1">1</td> <td class="style2">2</td>
  <td class="style0">3</td>
  <td class="style1">4</td> <td class="style2">5</td>
  <td class="style0">6</td>
  <td class="style1">7</td> <td class="style2">8</td>
  <td class="style0">9</td>
  <td class="style1">10</td> <td class="style2">11</td>
  <td class="style0">Noon</td>
  <td class="style2">1</td> <td class="style2">2</td>
  <td class="style0">3</td>
  <td class="style1">4</td> <td class="style2">5</td>
  <td class="style0">6</td>
  <td class="style1">7</td> <td class="style2">8</td>
  <td class="style0">9</td>
  <td class="style1">10</td> <td class="style2">11</td>
  <th>Tot:</th>
</tr>
"""
    )


def loadstations():
    """Bah"""
    for station in nt.sts:
        stData[station] = ["M"] * 25
        totp[station] = 0


@iemapp(help=__doc__)
def application(environ, start_response):
    """Go Main Go."""
    sio = StringIO()
    ts = doHeader(environ, start_response, sio)
    loadstations()
    setupTable(sio)

    td = ts.strftime("%Y-%m-%d")
    tm = (ts + timedelta(days=1)).strftime("%Y-%m-%d")

    sqlStr = """
        SELECT extract('hour' from valid) as vhour,
        id as station, valid, phour from hourly_%s h JOIN stations s on
        (h.iemid = s.iemid) WHERE
        valid > '%s 00:00' and valid <= '%s 00:00'
        and network in ('KCCI','KIMT','KELO')
    """ % (
        ts.year,
        td,
        tm,
    )
    pgconn, icursor = get_dbconnc("iem")

    icursor.execute(sqlStr)

    for row in icursor:
        p01i = float(row["phour"])
        vhour = int(row["vhour"])
        if p01i >= 0:  # We should require this timestep
            requireHrs[vhour] = 1
            try:
                stData[row["station"]][vhour] = round(p01i, 2)
            except KeyError:
                continue
        else:
            try:
                stData[row["station"]][vhour] = "&nbsp;"
            except KeyError:
                continue
    pgconn.close()

    j = 0
    ids = list(nt.sts.keys())
    ids.sort()
    for station in ids:
        j += 1
        sio.write(f'<tr class="row{j % 5}">')
        sio.write("%s%s%s" % ("<td>", nt.sts[station]["name"], "</td>"))
        for i in range(24):
            sio.write('<td class="style' + str(i % 3) + '">')
            sio.write("%s%s " % (stData[station][i], "</td>"))
            try:
                totp[station] = totp[station] + stData[station][i]
            except Exception:
                continue
        sio.write("%s%s%s" % ("<td>", totp[station], "</td>"))
        sio.write("%s%s%s" % ("<td>", station, "</td>"))
        sio.write("</tr>")

    sio.write(
        """
</table>

<p>Precipitation values are shown for the hour in which they are valid.  For
example, the value in the 1AM column is precipitation accumulation from 1 AM
till 2 AM.
"""
    )
    return [sio.getvalue().encode("ascii")]
