<?php
require_once "../../config/settings.inc.php";
define("IEM_APPID", 7);
require_once "../../include/myview.php";
require_once "../../include/mlib.php";
require_once "../../include/forms.php";
require_once "../../include/network.php";
require_once "../../include/database.inc.php";

$network = get_str404("network", 'IA_ASOS', 10);
$metar = get_str404("metar", "no");
$sortcol = get_str404("sortcol", "ts");
$sorder = get_str404("sorder", "desc");
$format = get_str404("format", "html");

$t = new MyView();
$t->title = "{$network} Current Conditions";
$t->refresh = 1200;
$t->iemselect2 = TRUE;
$t->current_network = "ASOS";

$nt = new NetworkTable($network, FALSE, TRUE);
$cities = $nt->table;
$mesosite = iemdb('mesosite');
$stname = iem_pg_prepare($mesosite, "SELECT tzname from networks where id = $1");
$rs = pg_execute($mesosite, $stname, array($network));
if (pg_num_rows($rs) < 1) {
    $tzname = "America/Chicago";
} else {
    $row = pg_fetch_assoc($rs, 0);
    $tzname = $row["tzname"];
}

$vals = array(
    "tmpf" => "Air Temperature [°F]", "dwpf" => "Dew Point Temp [°F]",
    "sknt" => "Wind Speed [knots]", "drct" => "Wind Direction [deg]",
    "alti" => "Altimeter [mb]", "peak" => "Today's Wind Gust [knots]",
    "peak_ts" => "Time of Peak Gust", "relh" => "Relative Humidity",
    "feel" => "Feels Like [°F]", "vsby" => "Visibility [miles]",
    "ts" => "Observation Time", "phour" => "Last Hour Rainfall [inch]",
    "min_tmpf" => "Today's Low Temperature", "name" => "Station Name",
    "max_tmpf" => "Today's High Temperature", "id" => "Station Identifier",
    "skyl1" => "Cloud Level 1",
    "skyl2" => "Cloud Level 2",
    "skyl3" => "Cloud Level 3",
    "skyl4" => "Cloud Level 4",
    "pday" => "Today Rainfall [inch]",
);
if (!array_key_exists($sortcol, $vals)) {
    $sortcol = "name";
}

$arr = array(
    "network" => $network,
);
$jobj = iemws_json("currents.json", $arr);

/* Final data array */
$mydata = array();

foreach ($jobj["data"] as $bogus => $iemob) {
    $key = $iemob["station"];
    $mydata[$key] = $iemob;
    $mydata[$key]["ts"] = new DateTime($iemob["local_valid"]);
    $mydata[$key]["sped"] = $mydata[$key]["sknt"] * 1.15078;
    if ($mydata[$key]["max_gust"] > $mydata[$key]["max_sknt"]) {
        $mydata[$key]["peak"] = $mydata[$key]["max_gust"];
        if (! is_null($mydata[$key]["local_max_gust_ts"])) {
            $mydata[$key]["peak_ts"] = new DateTime($mydata[$key]["local_max_gust_ts"]);
        }
    } else {
        $mydata[$key]["peak"] = $mydata[$key]["max_sknt"];
        if (! is_null($mydata[$key]["local_max_sknt_ts"])) {
            $mydata[$key]["peak_ts"] = new DateTime($mydata[$key]["local_max_sknt_ts"]);
        }
    }
} // End of while

if ($format == 'csv') {
    $csv = "station,valid_gmt,tmpf,max_tmpf,min_tmpf,dwpf,sknt,drct,relh,vsby,phour_in,pday_in,metar\n";
    foreach ($mydata as $key => $data) {
        $dt = new DateTime($data['utc_valid']);
        $csv .= sprintf(
            "%s,%s,%.0f,%.0f,%.0f,%.0f,%.0f,%.0f,%.1f,%s,%.2f,%.2f,%s\n",
            $key,
            $dt->format("Y-m-d H:i"),
            $data['tmpf'],
            $data["max_tmpf"],
            $data["min_tmpf"],
            $data['dwpf'],
            $data['sknt'],
            $data['drct'],
            $data['relh'],
            $data['vsby'],
            $data['phour'],
            $data['pday'],
            $data['raw']
        );
    }
    header("Content-type: text/plain");
    echo $csv;
    die();
}

$nselect = selectNetworkType("ASOS", $network);

$ar = array(
    "no" => "No",
    "yes" => "Yes"
);
$mselect = make_select("metar", $metar, $ar);

$ar = array(
    "asc" => "Ascending",
    "desc" => "Descending"
);
$sselect = make_select("sorder", $sorder, $ar);

$ar = array(
    "html" => "Web Page",
    "csv" => "Comma Delimited",
);
$fselect = make_select("format", $format, $ar);

$uri = "current.phtml?sorder=$sorder&metar=$metar&network=$network&sortcol=";

$year = date("Y");
$month = date("m");
$day = date("d");
$tkeys = array_keys($cities);
$station = $tkeys[0];
$table = <<<EOM
<table class="table table-bordered table-sm">
<tr>
  <td>
<form method="GET" action="current.phtml">
<input type="hidden" name="sortcol" value="{$sortcol}">
Select Network: {$nselect}</td>
  <td>Include METARS:<br />{$mselect}</td>
<td>Sort Order: {$sselect}</td>
<td>Format: {$fselect}</td></td>
<td><input type="submit" value="Go!"></form></td>
</tr></table>
<br />Times shown are for timezone: <strong>{$tzname}.</strong> The local day summary
is based on that timezone. <br />Table sorted by: <b>({$vals[$sortcol]})</b>
&nbsp; &nbsp; Click on
a column to sort it. Click on site ID for more information. You can download data from
this network <a href='/request/download.phtml?network={$network}'>here</a>
and you can view <a href="/sites/hist.phtml?station={$station}&network={$network}&mode=daily&year=$year&month=$month&day=$day">daily summaries</a>
on this network.

<form method="GET" action="/my/current.phtml">

<table class="table table-striped table-sm">
<thead class="sticky">
<tr>
  <th rowspan="2">ADD:</th>
  <th rowspan="2"><a href="{$uri}id">ID</a></th>
  <th rowspan="2"><a href="{$uri}name">Station</a></th>
  <th rowspan="2"><a href="{$uri}ts">Ob Time</a></th>
  <th rowspan="2">Present Wx</th>
  <th colspan="5">Temps &deg;F</th>
  <th colspan="3">&nbsp;</th>
  <th colspan="3">Wind [knots]</th>
  <th colspan="2">Precip</font></th>
  <th colspan="4">Clouds</font></th>
<tr>
  <th><a href="{$uri}tmpf">Air</a></th>
  <th><a href="{$uri}max_tmpf">Hi</a></th>
  <th><a href="{$uri}min_tmpf">Lo</a></th>
  <th><a href="{$uri}dwpf">Dewp</a></th>
  <th><a href="{$uri}feel">Feels</a></th>
  <th><a href="{$uri}relh">RH %</a></th>
  <th><a href="{$uri}alti">Alti</a></th>
  <th><a href="{$uri}vsby">Vsby</a></th>
  <th><a href="{$uri}sknt">Speed</a></th>
  <th><a href="{$uri}drct">Drct</a></th>
  <th><a href="{$uri}peak">Gust</a>
    @ <a href="{$uri}peak_ts">Time</a></th>
  <th><a href="{$uri}phour">1 Hour</a></th>
  <th><a href="{$uri}pday">Today</a></th>
  <th><a href="{$uri}skyl1">Level 1</a></th>
  <th><a href="{$uri}skyl2">Level 2</a></th>
  <th><a href="{$uri}skyl3">Level 3</a></th>
  <th><a href="{$uri}skyl4">Level 4</a></th>
</tr></thead>
<tbody>
EOM;

$finalA = aSortBySecondIndex($mydata, $sortcol, $sorder);
$now = time();
$i = 0;
$old = "";

$domain = array_keys($nt->table);
$online = array();

foreach ($finalA as $key => $parts) {
    // Keep track of online stations
    $online[] = $key;
    $i++;

    $row = "<tr";
    if ($i % 2 == 0)  $row .= " bgcolor='#eeeeee'";
    $row .= "><td><input type=\"checkbox\" name=\"st[]\" value=\"" . $key . "\"></td>";

    $tdiff = $now - strtotime($parts["utc_valid"]);
    $url = sprintf("/sites/site.php?station=%s&network=%s", $key, $network);
    $row .= sprintf("<td><a href='%s'>%s</a></td>", $url, $key);
    $row .= "<td>" . $cities[$key]["name"] . "</td>";
    $row .= "<td ";
    if ($tdiff > 10000) {
        $fmt = "d M h:i P";
        $row .= "bgcolor=\"red\">" . $parts["ts"]->format($fmt) . "</td><td colspan=\"18\">Site Offline</td></tr>";
        $old .= $row;
        continue;
    } else if ($tdiff > 7200) {
        $fmt = "h:i A";
        $row .= 'bgcolor="orange"';
    } else if ($tdiff > 3600) {
        $fmt = "h:i A";
        $row .= 'bgcolor="green"';
    } else {
        $fmt = "h:i A";
    }
    $phour = ($parts["phour"] != 0.0001) ? $parts["phour"] : 'T';
    $pday = ($parts["pday"] != 0.0001) ? $parts["pday"] : 'T';

    $ptmpf = ($parts["tmpf"] !== null) ? myround($parts["tmpf"], 0) : 'M';
    $pdwpf = ($parts["dwpf"] !== null) ? myround($parts["dwpf"], 0) : 'M';
    $pfeel = ($ptmpf === "M" || $pdwpf === "M" || $parts["feel"] === null) ? "M" : myround($parts["feel"], 0);
    $prelh = ($ptmpf === "M" || $pdwpf === "M" || $parts["relh"] === null) ? "M" : myround($parts["relh"], 0);
    $wxc = is_null($parts["wxcodes"]) ? "" : str_replace("{", " ", $parts["wxcodes"]);
    $row .= ">" . $parts["ts"]->format($fmt) . "</td>" .
        "<td align='center'>{$wxc}</td>" .
        "<td align='center'>" . $ptmpf . "</td><td><font color=\"#ff0000\">" . myround($parts["max_tmpf"], 0) . "</font></td><td><font color=\"#0000ff\">" . myround($parts["min_tmpf"], 0) . "</font></td>
     <td>" . $pdwpf . "</td>
     <td>" . $pfeel . "</td>
        <td>" . $prelh . "</td>
        <td>" . $parts["alti"] . "</td>
        <td>" . $parts["vsby"] . "</td>
             <td>" . myround($parts["sknt"], 0);

    if (floatval($parts["gust"] > 0)) {
        $row .= "G" . myround($parts["gust"], 0);
    }
    $row .= "</td>";
    $row .= "<td>" . drct2txt($parts["drct"]) . "</td><td>";
    if (isset($parts["peak_ts"])) {
        $row .= sprintf(
            "%s @ %s",
            myround($parts["peak"],0),
            $parts["peak_ts"]->format("h:i A"),
        );
    }
    $text_pday = $parts['pday'] == -99 ? 'M' : $parts['pday'];
    $row .= "</td><td>{$phour}</td>
            <td>{$pday}</td>
<td>" . $parts["skyc1"] . " " . $parts["skyl1"] . "</td>
<td>" . $parts["skyc2"] . " " . $parts["skyl2"] . "</td>
<td>" . $parts["skyc3"] . " " . $parts["skyl3"] . "</td>
<td>" . $parts["skyc4"] . " " . $parts["skyl4"] . "</td>
        </tr>\n";
    if ($metar == "yes") {
        $row .= "<tr";
        if ($i % 2 == 0)  $row .= " bgcolor='#eeeeee'";
        $row .= ">";
        $row .= "<td colspan=\"22\">
             <font color=\"brown\">" . $parts["raw"] . "</font></td>
             </tr>\n";
    }
    $table .= $row;
}

$offline = array_diff($domain, $online);
$offline_entries = "";
// loop over offline entries
foreach ($offline as $sid) {
    $sname = $nt->table[$sid]["name"];
    $url = sprintf("/sites/site.php?station=%s&network=%s", $sid, $network);
    $offline_entries .= sprintf(
        "<tr><td><input type=\"checkbox\" name=\"st[]\" value=\"%s\"></td>" .
            "<td><a href='%s'>%s</a></td>" .
            "<td>%s</td><td colspan=\"19\">Site Offline</td></tr>\n",
        $sid,
        $url,
        $sid,
        $sname
    );
}

$table .= $old;
$table .= $offline_entries;
$table .= <<<EOM
</tbody>

</table>

<input type="submit" value="Add to Favorites">
<input type="reset" value="Reset">

</form>
EOM;
$t->content = $table;
$t->render('sortables.phtml');
