<?php

require_once "../../../../config/settings.inc.php";
define("IEM_APPID", 49);
require_once "../../../../include/myview.php";
require_once "../../../../include/database.inc.php";
require_once "../../../../include/iemmap.php";
require_once "../../../../include/forms.php";
require_once "../../../../include/network.php";
require_once "../../../../include/vendor/mapscript.php";

$var = get_str404("var", "high");
$year = get_int404("year", date("Y"));
$month = get_int404("month", date("m"));
$day = get_int404("day", date("d"));
$source = get_str404("source", "prelim");
$size = get_str404("size", "1024x768");
$showlabels = (get_str404("labels", "off") == "on");
$timing = get_str404("timing", "1");
$state = get_str404("state", "IA");
$tokens = explode("x", $size);
$width = $tokens[0];
$height = $tokens[1];

$ts = new DateTime("{$year}-{$month}-{$day}");
$ndate = $ts->format("Y-m-d");

$t = new MyView();
$t->title = "NWS COOP Daily Plotter";

$ar = array(
    "0" => "All Available",
    "1" => "Morning Obs (5-11 AM)",
);
$timingsel = make_select("timing", $timing, $ar);

if ($source == "qc") $nt = new NetworkTable("{$state}CLIMATE");
else $nt = new NetworkTable("{$state}_COOP");
$cities = $nt->table;

/**
 * plot no data on the map
 *
 * @param mapObj $map
 * @param imageObj $img
 */
function plotNoData($map, $img)
{
    $layer = $map->getLayerByName("credits");

    $point = new pointObj();
    $point->setXY(100, 200);
    $point->draw(
        $map,
        $layer,
        $img,
        1,
        "  No data found for this date! "
    );
}

$vardef = array(
    "high" => "High Temperature",
    "low" => "Low Temperature",
    "tob" => "Temperature At Observation",
    "precip" => "Precipitation",
    "snow" => "Snow [1]",
    "snowd" => "Snow Depth [2]",
    "ratio" => "Snow to Liquid Ratio",
);
if (!array_key_exists($var, $vardef)) {
    $var = "precip";
}
$pcols = Array("precip", "snow", "snowd", "ratio");
$timecol = in_array($var, $pcols) ? "precip_hour" : "temp_hour";

$rnd = array(
    "et" => 2,
    "prec" => 2,
    "snow" => 0,
    "ratio" => 1
);

$myStations = $cities;

$map = new mapObj("../../../../data/gis/base4326.map");
$map->imagecolor->setRGB(255, 255, 255);
$map->selectOutputFormat("PNG24");
$map->setSize($width, $height);
$dbconn = iemdb("postgis");
$stname = iem_pg_prepare(
    $dbconn,
    "SELECT ST_xmin(the_geom), ST_xmax(the_geom), ST_ymin(the_geom), ST_ymax(the_geom) ".
    "from states where state_abbr = $1");
$rs = pg_execute($dbconn, $stname, Array($state));
$row = pg_fetch_assoc($rs, 0);
$buf = 0.5;
$map->setextent(
    $row["st_xmin"] - $buf,
    $row["st_ymin"] - $buf,
    $row["st_xmax"] + $buf,
    $row["st_ymax"] + $buf
);

$states = $map->getLayerByName("states");
$states->status = MS_ON;
$states_c0 = $states->getClass(0);
$states_c0_s0 = $states_c0->getStyle(0);
$states_c0_s0->width = 1.5;
$states_c0_s0->color->setRGB(210, 170, 130);

$cwas = $map->getLayerByName("cwas");
$cwas->status = MS_ON;
$cwas_c0 = $cwas->getClass(0);
$cwas_c0_s0 = $cwas_c0->getStyle(0);
$cwas_c0_s0->outlinecolor->setRGB(255, 0, 0);

$counties = $map->getLayerByName("uscounties");
$counties->__set("status", MS_ON);
$counties_c0 = $counties->getClass(0);
$counties_c0_s0 = $counties_c0->getStyle(0);
$counties_c0_s0->color->setRGB(180, 180, 180);

$snet = $map->getLayerByName("datapoint");
$snet->__set("status", MS_ON);

$ponly = $map->getLayerByName("pointonly");
$ponly->__set("status", MS_ON);

$cityname = $map->getLayerByName("cityname");
$cityname->__set("status", MS_ON);

$img = $map->prepareImage();
$counties->draw($map, $img);
$states->draw($map, $img);
$cwas->draw($map, $img);

$dbvar = ($var == "ratio") ? "snow" : $var;
$timingsql = "";
if ($source == "qc") {
    $c = iemdb("coop");
    if ($timing == "1") {
        $timingsql = " and temp_hour between 4 and 12 ";
    }
    $dbargs = Array($ts->format("Y-m-d"));
    $sql = <<<EOM
    SELECT *, $timecol as hour from alldata_{$state}
    WHERE day = $1 and {$dbvar} is not null
    and substr(station, 3, 1) not in ('C', 'D', 'T')
    and substr(station, 3, 4) != '0000' $timingsql ORDER by $dbvar DESC
EOM;
    $cutstring1 = 2;
    $cutstring2 = 4;
} else {
    $c = iemdb("iem");
    $cutstring1 = 0;
    $cutstring2 = 5;
    if ($timing == "1") {
        $timingsql = " and extract(hour from coop_valid) between 4 and 12 ";
    }
    $dbargs = Array($ts->format("Y-m-d"), "{$state}_COOP");
    $sql = <<<EOM
    SELECT id as station, day, snowd, max_tmpf as high,
    extract(hour from coop_valid) as hour,
    min_tmpf as low, pday as precip, snow, snowd, coop_tmpf as tob
    from summary_{$ts->format('Y')} s JOIN stations t on (t.iemid = s.iemid)
    WHERE day = $1 and network = $2 $timingsql ORDER by $dbvar DESC
EOM;
}

$stname = iem_pg_prepare($c, $sql);
$rs =  pg_execute($c, $stname, $dbargs);
$vals = array();
while ($row = pg_fetch_assoc($rs)) {
    $stid = $row['station'];
    if ($var == "ratio") {
        if ($row["snow"] > 0 && $row["precip"] > 0) {
            $vals[$stid] = Array(
                "val" => round($row["snow"] / $row["precip"], 1),
                "hour" => $row["hour"],
            );
        } else {
            $vals[$stid] = Array("val" => 0, "hour" => $row["hour"]);
        }
    } else {
        if (is_null($row[$var])) continue;
        $vals[$stid] = Array(
            "val" => (float)$row[$var],
            "hour" => $row["hour"],
        );
    }
}
/* ------------------------------------------------------- */


$tr = "# " . $ndate . " " . $vardef[$var] . "
# Download From: {$EXTERNAL_BASEURL}/GIS/apps/coop/plot.phtml
# Download Date: " . date("d M Y") . "
# Data Contact: Daryl Herzmann akrherz@iastate.edu 515.294.5978
#-----------------------snip------------------\n";
$tr .= sprintf(
    "%-6s, %-20s, %-20s, %-10s, %10s, %10s, %4s, %10s\n",
    'ID',
    'StationName',
    'County',
    'Date',
    'Latitude',
    'Longitude',
    'Hour',
    $var
);
foreach ($vals as $key => $value) {
    $ukey = strtoupper($key);
    if (!isset($cities[$ukey])) continue;

    $tr .= sprintf(
        "%-6s, %-20s, %-20s, %10s, %10.4f, %10.4f, %4s, %10s\n",
        $key,
        $cities[$ukey]['name'],
        $cities[$ukey]['county'],
        $ndate,
        $cities[$ukey]['lat'],
        $cities[$ukey]['lon'],
        $value["hour"],
        $value["val"],
    );

    if ($showlabels) {
        $pt = new pointObj();
        $pt->setXY($cities[$ukey]['lon'], $cities[$ukey]['lat'], 0);
        $pt->draw($map, $ponly, $img, 0, "");

        $pt = new pointObj();
        $pt->setXY($cities[$ukey]['lon'], $cities[$ukey]['lat'], 0);
        $pt->draw($map, $cityname, $img, 0, substr($key, $cutstring1, $cutstring2));
    }

    // Value UL
    $pt = new pointObj();
    $pt->setXY($cities[$ukey]['lon'], $cities[$ukey]['lat'], 0);
    if ($value["val"] == 0.0001) $value["val"] = "T";
    $pt->draw($map, $snet, $img, 0, $value["val"]);
}

if (pg_num_rows($rs) == 0)
    plotNoData($map, $img);

iemmap_title($map, $img, $ndate . " " . $vardef[$var]);
$map->drawLabelCache($img);

$url = saveWebImage($img);

$ar = array(
    "qc" => "Quality Controlled / climodat (1893-)",
    "prelim" => "Preliminary (2004+)"
);
$sourceselect = make_select("source", $source, $ar);

$varselect = make_select("var", $var, $vardef);

$yselect = yearselect(1893, $year);
$mselect = monthSelect($month, 'month');
$dselect = daySelect($day, 'day');

$ar = array(
    "640x480" => "640x480",
    "1024x768" => "1024x768",
    "1280x1024" => "1280x1024"
);
$sizeselect = make_select("size", $size, $ar);

$showlabelson = ($showlabels) ? " CHECKED=\"CHECKED\" " : "";

$sselect = stateSelect($state);
$yest = clone $ts;
$yest->sub(new DateInterval("P1D"));
$minusone = sprintf(
    "plot.phtml?source=%s&amp;var=%s&amp;year=%s&amp;" .
        "month=%s&amp;day=%s&amp;size=%s&amp;labels=%s&amp;timing=%s&amp;state=%s",
    $source,
    $var,
    $yest->format("Y"),
    $yest->format("m"),
    $yest->format("d"),
    $size,
    $showlabels ? "on" : "off",
    $timing,
    $state,
);
$tomorrow = clone $ts;
$tomorrow->add(new DateInterval("P1D"));
$plusone = sprintf(
    "plot.phtml?source=%s&amp;var=%s&amp;year=%s&amp;" .
        "month=%s&amp;day=%s&amp;size=%s&amp;labels=%s&amp;timing=%s&amp;state=%s",
    $source,
    $var,
    $tomorrow->format("Y"),
    $tomorrow->format("m"),
    $tomorrow->format("d"),
    $size,
    $showlabels ? "on" : "off",
    $timing,
    $state,
);

$t->content = <<<EOM

<p>
This application plots the once daily long term climate sites for a given
date.  The IEM maintains two datasets in this space.  The first being the
preliminary NWS COOP observations, which dates back to 2004 or so. For this
dataset, an <a href="/COOP/map/">interactive map</a> exists. The second
being a more quality controlled and gap-filled dataset called "climodat". This
data goes back much further.
</p>

<form method="GET" name="myform">
<table class="table table-bordered">
 <tr>
    <th>Select State:</th>
   <th>Select Datasource:</th>
   <th>Select Parameter:</th>
   <th>Timing</th>
   <th>Year</th>
   <th>Month</th>
   <th>Day</th>
   <th>Image Size</th>
   <td></td>
  </tr>
 <tr>
  <td>{$sselect}</td>
  <td>{$sourceselect}</td>
  <td>{$varselect}
  <br /><i>Note:</i> Temperature at Observation is only available for the
  "Preliminary" data source.
  </td>
  <td>{$timingsel}</td>
  <td>{$yselect}</td>
  <td>{$mselect}</td>
  <td>{$dselect}</td>
  <td>{$sizeselect}</td>
  <td><input type="submit" value="Make Plot">
    <a href="{$minusone}" class="btn btn-secondary"><i class="bi bi-dash" aria-hidden="true"></i> 1 Day</a>
    <a href="{$plusone}" class="btn btn-secondary"><i class="bi bi-plus" aria-hidden="true"></i> 1 Day</a>
  </td>
  </tr>
</table>

<br /><img src="{$url}">

<p><input type="checkbox" name="labels"{$showlabelson}>Show point labels

</form>
<ul>
<li>Snowfall data is not complete.  Please be careful using the data.</li>
<li>Snowfall depth data only goes back to 1991 for Quality Controled source.</li>
<li>The preliminary data is for the date the observation was reported and not
necessarily for the local date.  The reports are around 7 AM, so the high
temperature (for example) was most likely for the previous date.</li>
</ul>

<p>
<img src="/images/gisready.png"><h3> Data Listing</h3>
<pre>{$tr}</pre>

<p>You should be able to 'copy & paste' this raw data listing into a simple
text editor and save the data file on your machine.  Most GIS systems can
then import this dataset as a layer.  You may have to omit the commented lines
(#) if your GIS has trouble importing the data.
EOM;
$t->render('single.phtml');
