<?php
require_once "../../config/settings.inc.php";
require_once "../../include/myview.php";
require_once "../../include/forms.php";
require_once "../../include/database.inc.php";

$t = new MyView();
$uri = 'mcview.phtml';
$postgis = iemdb("postgis");

$stname = iem_pg_prepare(
    $postgis,
    "select * from watches " .
        "WHERE issued <= $1 and expired >= $1 ORDER by sel ASC"
);

/** Import our variables */
$prod = get_str404("prod", "comprad");
$java = get_str404("java", "script");
$mode = get_str404("mode", "realtime");
$frames = get_int404("frames", 13);
$interval = get_int404("interval", 5);
$autopilot = get_str404("autopilot", "no");

/* Lets see what the form is set to */
$year = get_int404("year", date("Y"));
$month = get_int404("month", date("m"));
$day = get_int404("day", date("d"));
$hour = get_int404("hour", date("H"));
$minute = get_int404("minute", date("i"));

// Used for the info presented below the plot on getting the raw data
$gissource = ($year > 2014) ? 'n0q' : 'n0r';
$gissourcenum = ($year > 2014) ? '2' : '1';

/** Acceptable number of frames are between 1 and 10000 */
if (intval($frames) > 10000 || intval($frames) < 1) $frames = 13;
/** Acceptable interval is between 5 and 60 */
if (intval($interval) > 60 || intval($interval) < 5) $interval = 5;

$jan2007 = mktime(0, 0, 0, 1, 1, 2007);
$astart = array(
    "comprad" => mktime(0, 0, 0, 1, 1, 1995),
    "usrad" => mktime(0, 0, 0, 1, 1, 1995),
    "ictrad" => mktime(0, 0, 0, 1, 1, 1995),
    "hunrad" => mktime(0, 0, 0, 1, 1, 1995),
    "sdrad" => mktime(0, 0, 0, 1, 1, 1995),
    "sel0rad" => $jan2007,
    "sel1rad" => $jan2007,
    "sel2rad" => $jan2007,
    "sel3rad" => $jan2007,
    "sel4rad" => $jan2007,
    "sel5rad" => $jan2007,
    "sel6rad" => $jan2007,
    "sel7rad" => $jan2007,
    "sel8rad" => $jan2007,
    "sel9rad" => $jan2007,
    "lotrad" => mktime(0, 0, 0, 1, 1, 1995)
);
if (!array_key_exists($prod, $astart)) {
    die405();
}

$now = time() - 60;
$aend = time();

/* Figure when the lapse starts! $ts */
if ($mode == "realtime") {
    $ts = $now - ($frames - 1) * (intval($interval) * 60);
} else { /* Historical */
    $ots = mktime($hour, $minute, 0, $month, $day, $year);
    /* Make sure archive request is not sooner than archive start */
    if ($ots < $astart[$prod])
        $ts = $astart[$prod];
    /* Make sure archive request is not in the future */
    else if ($ots > $now)
        $ts = $now - (($frames) * (intval($interval) * 60));
    /* Set the timestamp */
    else
        $ts = $ots;
}

$rs = pg_execute($postgis, $stname, array(date("Y-m-d H:i", $ts)));
$watches = "<div style=\"border: 1px solid #000; padding-left: 10px; background: #eee; width: 100%;\"><strong>Valid Watches:</strong> ";
while ($row = pg_fetch_assoc($rs)) {
    $issued = strtotime($row["issued"]);
    $watches .= sprintf(
        "<a href=\"mcview.phtml?prod=%srad&java=none&mode=%s&frames=1&interval=5&year=%s&month=%s&day=%s&hour=%s&minute=%s\">%s (%s %s)</a> &nbsp; ",
        trim(strtolower(is_null($row["sel"]) ? "": $row["sel"])),
        $mode,
        $year,
        $month,
        $day,
        $hour,
        $minute,
        $row["sel"],
        $row["type"],
        $row["num"]
    );
}
if (pg_num_rows($rs) == 0) {
    $watches .= " <i>None valid for the selected time</i> ";
}
$watches .= "</div>";


// This is what we set the form time to
$formts = $ts;

$ar = localtime($ts);
$m = $ar[1];

if ($m >= 55) $ma = "55";
else if ($m >= 50) $ma = "50";
else if ($m >= 45) $ma = "45";
else if ($m >= 40) $ma = "40";
else if ($m >= 35) $ma = "35";
else if ($m >= 30) $ma = "30";
else if ($m >= 25) $ma = "25";
else if ($m >= 20) $ma = "20";
else if ($m >= 15) $ma = "15";
else if ($m >= 10) $ma = "10";
else if ($m >= 5) $ma = "05";
else if ($m >= 0) $ma = "00";

$diff = $m - intval($ma);

$hour  = date("H", $formts);
$day   = date("d", $formts);
$month = date("m", $formts);
$year  = date("Y", $formts);
$minute = $ma;

/* Our actual loop start time! */
$loopts = $ts - ($diff * 60);
$lwidth = 650;
$lheight = 550;

$images = array();
$radtimes = array();
for ($i = 0; $i < intval($frames); $i++) {
    $fts = $loopts + ($i * (intval($interval) * 60));
    if ($fts > time()) {
        continue;
    }
    $myuri = "/archive/data/" . gmdate('Y/m/d/', $fts) . "$prod/n0r_" .
        gmdate('Ymd_Hi', $fts) . ".png";
    $myhref = "/archive/data/" . gmdate('Y/m/d/', $fts) . "GIS/uscomp/n0r_" .
        gmdate('YmdHi', $fts) . ".png";
    $gisbase = "/archive/data/" . gmdate('Y/m/d/', $fts) . "GIS/uscomp/";
    $images[] = $myuri;
    $radtimes[] = $fts;
}

$ar = array(
    "comprad" => "A1. Iowa (Default)",
    "usrad" => "A1. United States",
    "hunrad" => "A1. Huntsville, AL",
    "lotrad" => "A1. North Illinois",
    "sdrad" => "A1. South Dakota",
    "ictrad" => "A1. Wichita, KS",
    "sel0rad" => "A3. Watch (SEL0)",
    "sel1rad" => "A3. Watch (SEL1)",
    "sel2rad" => "A3. Watch (SEL2)",
    "sel3rad" => "A3. Watch (SEL3)",
    "sel4rad" => "A3. Watch (SEL4)",
    "sel5rad" => "A3. Watch (SEL5)",
    "sel6rad" => "A3. Watch (SEL6)",
    "sel7rad" => "A3. Watch (SEL7)",
    "sel8rad" => "A3. Watch (SEL8)",
    "sel9rad" => "A3. Watch (SEL9)",
);
$prodselect = make_select("prod", $prod, $ar);

$ar = array(
    "script" => "Java Script",
    "none" => "List Images",
);
$loopselect = make_select("java", $java, $ar);

$ar = array(
    "realtime" => "Real Time",
    "archive" => "Archived",
);
$modeselect = make_select("mode", $mode, $ar);

$ar = array(
    "5" => "5 Min (Default)",
    "10" => "10 min",
    "15" => "15 min",
    "20" => "20 min",
    "30" => "30 min",
    "60" => "60 min",
);
$intselect = make_select("interval", $interval, $ar);

$start = intval(1995);
$now = new DateTime();
$tyear = $now->format("Y");
$dateselect = "<select name='year'>\n";
for ($i = $start; $i <= $tyear; $i++) {
    $dateselect .= "<option value='" . $i . "' ";
    if ($i == intval($year)) $dateselect .= "SELECTED";
    $dateselect .= ">" . $i . "\n";
}
$dateselect .= "</select>\n";

$dateselect .= "<select name='month'>\n";
for ($i = 1; $i <= 12; $i++) {
    $ts = new DateTime("2000-$i-01");
    $dateselect .= "<option value='" . $i . "' ";
    if ($i == intval($month)) $dateselect .= "SELECTED";
    $dateselect .= ">" . $ts->format("M") . "\n";
}
$dateselect .= "</select>\n";

$dateselect .= "<select name='day'>\n";
for ($k = 1; $k < 32; $k++) {
    $dateselect .= "<option value=\"" . $k . "\" ";
    if ($k == (int)$day) {
        $dateselect .= "SELECTED";
    }
    $dateselect .= ">" . $k . "\n";
}
$dateselect .= "</select>\n";


$timeselect = "<select name='hour'>\n";
for ($i = 0; $i < 24; $i++) {
    $ts = new DateTime("2000-01-01 $i:00");
    $timeselect .= "<option value='{$i}' ";
    if ($i == intval($hour)) $timeselect .= "SELECTED";
    $timeselect .= ">" . $ts->format("h A") . "\n";
}
$timeselect .= "</select>\n";

$timeselect .= "<select name='minute'>\n";
for ($i = 0; $i < 60; $i = $i + 5) {
    $timeselect .= "<option value='{$i}' ";
    if ($i == intval($minute)) $timeselect .= "SELECTED";
    $timeselect .= sprintf(">%02d\n", $i);
}
$timeselect .= "</select>\n";

$autoselected = ($autopilot == "yes") ? " checked=\"checked\"" : "";
$rtmessage = ($mode == "realtime") ? " &nbsp; <b>REAL-TIME mode:</b> Will refresh in 5 minutes" : "";

$headextra = "";

if ($java == 'script') {
    $t->jsani = true;
    $i = 0;
    $jsurls = '<ul id="iemjsani_frames" style="display: none;">';
    foreach ($images as $key => $val) {
        $jsurls .= sprintf("<li>%s</li>\n", $val);
    }
    $jsurls .= "</ul>";
    $control = <<<EOM
{$jsurls}
<p><div id="iemjsani" style="width: 800px; height: 640px;"></div></p>
EOM;
} else {
    reset($images);
    $control = "";
    foreach ($images as $key => $val) {
        $control .= "<p><img src=\"{$val}\" class=\"img-fluid\">\n";
    }
}

$radlinks = "";
foreach ($radtimes as $value) {
    $myhref = "/archive/data/" . gmdate('Y/m/d/', $value) . "GIS/uscomp/{$gissource}_" . gmdate('YmdHi', $value) . ".png";
    $myhref2 = "{$EXTERNAL_BASEURL}{$myhref}";
    $radlinks .= "<li><a href='$myhref'>$myhref2</a> " .
        "(<a href='/request/gis/{$gissource}2gtiff.php?dstr=" . gmdate('YmdHi', $value) . "'>GeoTiff</a> or " .
        "<a href=\"/cgi-bin/request/raster2netcdf.py?dstr=" . gmdate('YmdHi', $value) . "&prod=composite_{$gissource}\">netCDF</a>)</li>\n";
}

/* We finally start output */

if ($autopilot == "yes") {
    $headextra .= <<<EOM
<style>
body{
  background: #fff;
}
#iem-header{
 display: none;
}
.iembox{
 display: none;
}
</style>
EOM;
}
$t->headextra = $headextra;
if ($mode == "realtime") {
    $t->refresh = 300;
}
$t->title = "Current & Historical IEM NEXRAD Mosaic Loop";

$t->content = <<<EOM
<nav aria-label="breadcrumb">
 <ol class="breadcrumb">
 <li class="breadcrumb-item"><a href="/current/">Current Data</a></li>
 <li class="breadcrumb-item active"><b>IEM NEXRAD Mosaic</b> <a href="{$uri}">Reset Application for a Current Loop</a></li>
 </ol>
</nav>

<p><div class="alert alert-info">
<i class="bi bi-chat"></i>
If you like this page,
you may also like the <a href="/one/">IEM One</a> app.  Please try it out and
<a href="/info/contacts.php">provide feedback</a>!</div>

<div class="row">
<div class="col-md-9">

{$watches}

{$rtmessage}

{$control}

</div>
<div class="col-md-3">

<form method="GET" action="{$uri}" name="controls">

<p><strong>Composite Product:</strong><br />
{$prodselect}

<br />(<i>Archive Begins @</i>)
<br /><b>Al.</b> 1 Jan 1995
<br /><b>A2.</b> 21 Sep 2005
<br /><b>A3.</b> 1 Jan 2007

<p><strong>Display Tool:</strong><br />
{$loopselect}

<p><strong>Mode:</strong></br />
{$modeselect}

<p><strong>Frames:</strong><br />
<input type="text" size="5" name="frames" value="{$frames}" class="form-control">

<p><strong>Frame Interval:</strong><br />
{$intselect}

<p><strong>Date:</strong><br />
{$dateselect}
<p><strong>Time:</strong><br />
{$timeselect}

<p><div class="form-check">
<input type="checkbox" value="yes" name="autopilot"{$autoselected} class="form-check-input" id="autopilot">
<label class="form-check-label" for="autopilot">Hide menus + header</label>
</div>

<p><input type="submit" value="Generate Loop" class="btn btn-primary">

<p><strong>Related Links:</strong><br />
<a href="/GIS/apps/rview/warnings.phtml">Interactive RADAR</a>
<br /><a href="/cow/">Warning Verification</a>
</form>

</div></div>

<br />
<p><b>GIS NEXRAD layers</b>
<br />The NEXRAD layer used in these images are available in a georeferenced
RASTER format. You will need this
<a href="/data/gis/images/4326/USCOMP/{$gissource}_0.wld">this world file</a>
to correctly georeference them.  The projection of
these images is geographic NAD83 (<i>unprojected</i>).  You will need to
rename the world file to match the filename of the RADAR layer before loading
into your GIS.  You may also be interested in the <a href="/GIS/rasters.php?rid={$gissourcenum}">conversion</a> of
color index values to dBZ and <a href="/docs/nexrad_mosaic/">more details</a>
on these mosaics.</p>
<br>
<ul>
{$radlinks}
</ul>
EOM;
$t->jsextra = '<script type="module" src="mcview.module.js"></script>';
$t->render('single.phtml');
