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

$t = new MyView();
$t->title = "Storm Based Warning Stats";
$t->headextra = <<<EOM
<link rel="stylesheet" type="text/css" href="sbwstats.css">
EOM;

$nt = new NetworkTable("WFO", TRUE);
$postgis = iemdb("postgis");

$syear = get_int404("syear", date("Y", time() - 86400));
$eyear = get_int404("eyear", date("Y", time() - 86400));
$smonth = get_int404("smonth", date("m", time() - 86400));
$sday = get_int404("sday", date("d", time() - 86400));
$shour = get_int404("shour", 0);
$emonth = get_int404("emonth", date("m"));
$eday = get_int404("eday", date("d"));
$ehour = get_int404("ehour", 0);

$sortby = isset($_GET["sortby"]) ? xssafe($_GET["sortby"]) : "wfo";
$sts = mktime($shour, 0, 0, $smonth, $sday, $syear);
$ets = mktime($ehour, 0, 0, $emonth, $eday, $eyear);
$gis_url = sprintf(
    "/cgi-bin/request/gis/watchwarn.py?limit1=yes&amp;" .
        "year1=%s&amp;month1=%s&amp;day1=%s&amp;hour1=%s&amp;minute1=0&amp;" .
        "year2=%s&amp;month2=%s&amp;day2=%s&amp;hour2=%s&amp;minute2=0",
    date("Y", $sts),
    date("m", $sts),
    date("d", $sts),
    date("H", $sts),
    date("Y", $ets),
    date("m", $ets),
    date("d", $ets),
    date("H", $ets)
);

$stname = iem_pg_prepare($postgis, "SELECT wfo, phenomena, count(*) as cnt,
  sum( st_area2d( ST_transform(geom,9311) ) ) as sum_polysize,
  avg( st_area2d( ST_transform(geom,9311) ) ) as avg_polysize,
  sum( st_perimeter( ST_transform(geom,9311) ) ) as sum_perimsize,
  avg( st_perimeter( ST_transform(geom,9311) ) ) as avg_perimsize
  from sbw WHERE status = 'NEW' and 
  phenomena IN ('SV','TO','MA','FF','FA','DS','SQ') and significance = 'W'
  and issue BETWEEN $1 and $2 GROUP by wfo, phenomena ORDER by $sortby ASC");

pg_query($postgis, "SET TIME ZONE 'UTC'");
$rs = pg_execute(
    $postgis,
    $stname,
    array(date('Y-m-d H:i', $sts), date('Y-m-d H:i', $ets))
);

$data = array();
$sorted = array();
$suffixes = array("cnt", "sum_polysize", "sum_perimsize", "avg_polysize", "avg_perimsize");
$phenoms = array("SV", "TO", "MA", "FF", "FA", "DS", "SQ");
while ($row = pg_fetch_assoc($rs)) {
    $wfo = $row["wfo"];
    if (!array_key_exists($wfo, $data)) {
        $sorted[] = $wfo;
        $data[$wfo] = array();
        foreach ($phenoms as $k => $p) {
            foreach ($suffixes as $k => $s) {
                $data[$wfo]["{$p}_$s"] = 0;
            }
        }
    }
    $data[$wfo][$row["phenomena"] . "_sum_polysize"] = $row["sum_polysize"];
    $data[$wfo][$row["phenomena"] . "_sum_perimsize"] = $row["sum_perimsize"];
    $data[$wfo][$row["phenomena"] . "_avg_polysize"] = $row["avg_polysize"];
    $data[$wfo][$row["phenomena"] . "_avg_perimsize"] = $row["avg_perimsize"];
    $data[$wfo][$row["phenomena"] . "_cnt"] = $row["cnt"];
}

$table = "
<table border=\"1\" class=\"table\">
<caption>Data valid for warnings issued between " . date('d M Y H:i', $sts) . " and " . date('d M Y H:i', $ets) . " UTC</caption>
<thead class=\"sticky\">
<tr>
  <th colspan='2'>Weather Forecast Office</th>
  <th colspan='3'>Summary</th>
  <th colspan='3' class='phto'>Tornado</th>
  <th colspan='3' class='phsv'>Severe Thunderstorm</th>
  <th colspan='3' class='phma'>Marine</th>
  <th colspan='3' class='phff'>Flash Flood</th>
  <th colspan='3' class='phfa'>Areal Flood</th>
  <th colspan='3' class='phds'>Dust Storm</th>
  <th colspan='3' class='phsq'>Snow Squall</th>
</tr>
<tr>
 <th>ID</th><th>Name</th>
 <th>Cnt</th><th>Perim</th><th>Area</th>
 <th class='phto'>Cnt</th><th class='phto'>Perim</th><th class='phto'>Area</th>
 <th class='phsv'>Cnt</th><th class='phsv'>Perim</th><th class='phsv'>Area</th>
 <th class='phma'>Cnt</th><th class='phma'>Perim</th><th class='phma'>Area</th>
 <th class='phff'>Cnt</th><th class='phff'>Perim</th><th class='phff'>Area</th>
 <th class='phfa'>Cnt</th><th class='phfa'>Perim</th><th class='phfa'>Area</th>
 <th class='phds'>Cnt</th><th class='phds'>Perim</th><th class='phds'>Area</th>
 <th class='phsq'>Cnt</th><th class='phsq'>Perim</th><th class='phsq'>Area</th>
</tr>
</thead>
<tbody>
";
$totals = array(
    "TO_cnt" => 0, "TO_perim" => 0, "TO_area" => 0,
    "SV_cnt" => 0, "SV_perim" => 0, "SV_area" => 0,
    "MA_cnt" => 0, "MA_perim" => 0, "MA_area" => 0,
    "FF_cnt" => 0, "FF_perim" => 0, "FF_area" => 0,
    "FA_cnt" => 0, "FA_perim" => 0, "FA_area" => 0,
    "DS_cnt" => 0, "DS_perim" => 0, "DS_area" => 0,
    "SQ_cnt" => 0, "SQ_perim" => 0, "SQ_area" => 0,
);
foreach ($sorted as $v => $wfo) {
    foreach ($phenoms as $idx => $phenom) {
        $totals["{$phenom}_cnt"] += $data[$wfo]["{$phenom}_cnt"];
        $totals["{$phenom}_perim"] += $data[$wfo]["{$phenom}_sum_perimsize"];
        $totals["{$phenom}_area"] += $data[$wfo]["{$phenom}_sum_polysize"];
    }

    $cnt = $data[$wfo]["TO_cnt"] +
        $data[$wfo]["SV_cnt"] +
        $data[$wfo]["MA_cnt"] +
        $data[$wfo]["FA_cnt"] +
        $data[$wfo]["FF_cnt"] +
        $data[$wfo]["DS_cnt"] +
        $data[$wfo]["SQ_cnt"];
    $perim = $data[$wfo]["TO_sum_perimsize"] +
        $data[$wfo]["SV_sum_perimsize"] +
        $data[$wfo]["MA_sum_perimsize"] +
        $data[$wfo]["FA_sum_perimsize"] +
        $data[$wfo]["FF_sum_perimsize"] +
        $data[$wfo]["DS_sum_perimsize"] +
        $data[$wfo]["SQ_sum_perimsize"];
    $poly = $data[$wfo]["TO_sum_polysize"] +
        $data[$wfo]["SV_sum_polysize"] +
        $data[$wfo]["MA_sum_polysize"] +
        $data[$wfo]["FA_sum_polysize"] +
        $data[$wfo]["FF_sum_polysize"] +
        $data[$wfo]["DS_sum_polysize"] +
        $data[$wfo]["SQ_sum_polysize"];

    $counts = array();
    foreach ($phenoms as $k => $p) {
        $counts[$p] = max(1, $data[$wfo]["{$p}_cnt"]);
    }
    $table .= sprintf(
        "<tr><td>%s</td><td>%s</td>
         <td>%s</td><td>%.1f</td><td>%.1f</td>
         <td class='phto'>%s</td><td class='phto'>%.1f</td><td class='phto'>%.1f</td>
         <td class='phsv'>%s</td><td class='phsv'>%.1f</td><td class='phsv'>%.1f</td>
         <td class='phma'>%s</td><td class='phma'>%.1f</td><td class='phma'>%.1f</td>
         <td class='phff'>%s</td><td class='phff'>%.1f</td><td class='phff'>%.1f</td>
         <td class='phfa'>%s</td><td class='phfa'>%.1f</td><td class='phfa'>%.1f</td>
         <td class='phds'>%s</td><td class='phds'>%.1f</td><td class='phds'>%.1f</td>
         <td class='phsq'>%s</td><td class='phsq'>%.1f</td><td class='phsq'>%.1f</td>
          </tr>",
        $wfo,
        $nt->table[$wfo]['name'],
        $cnt,
        $perim / $cnt / 1000.0,
        $poly / $cnt / 1000000.0,
        $data[$wfo]["TO_cnt"],
        $data[$wfo]["TO_sum_perimsize"] / $counts["TO"] / 1000.0,
        $data[$wfo]["TO_sum_polysize"] / $counts["TO"] / 1000000.0,
        $data[$wfo]["SV_cnt"],
        $data[$wfo]["SV_sum_perimsize"] / $counts["SV"] / 1000.0,
        $data[$wfo]["SV_sum_polysize"] / $counts["SV"] / 1000000.0,
        $data[$wfo]["MA_cnt"],
        $data[$wfo]["MA_sum_perimsize"] / $counts["MA"] / 1000.0,
        $data[$wfo]["MA_sum_polysize"] / $counts["MA"] / 1000000.0,
        $data[$wfo]["FF_cnt"],
        $data[$wfo]["FF_sum_perimsize"] / $counts["FF"] / 1000.0,
        $data[$wfo]["FF_sum_polysize"] / $counts["FF"] / 1000000.0,
        $data[$wfo]["FA_cnt"],
        $data[$wfo]["FA_sum_perimsize"] / $counts["FA"] / 1000.0,
        $data[$wfo]["FA_sum_polysize"] / $counts["FA"] / 1000000.0,
        $data[$wfo]["DS_cnt"],
        $data[$wfo]["DS_sum_perimsize"] / $counts["DS"] / 1000.0,
        $data[$wfo]["DS_sum_polysize"] / $counts["DS"] / 1000000.0,
        $data[$wfo]["SQ_cnt"],
        $data[$wfo]["SQ_sum_perimsize"] / $counts["SQ"] / 1000.0,
        $data[$wfo]["SQ_sum_polysize"] / $counts["SQ"] / 1000000.0
    );
}

$tcount = $totals["TO_cnt"] + $totals["SV_cnt"] + $totals["MA_cnt"] +
    $totals["FF_cnt"] + $totals["FA_cnt"] + $totals["DS_cnt"] + $totals["SQ_cnt"];
$tpoly = $totals["TO_area"] + $totals["SV_area"] + $totals["MA_area"] +
    $totals["FF_area"] + $totals["FA_area"] + $totals["DS_area"] + $totals["SQ_area"];
$tperim = $totals["TO_perim"] + $totals["SV_perim"] + $totals["MA_perim"] +
    $totals["FF_perim"] + $totals["FA_perim"] + $totals["DS_perim"] + $totals["SQ_perim"];

$counts = array();
foreach ($phenoms as $k => $p) {
    $counts[$p] = max(1, $totals["{$p}_cnt"]);
}

function mydiv($numer, $demon){
    if (is_null($demon) || $demon == 0){
        return 0;
    }
    return $numer / $demon;
}

$table .= sprintf(
    "<tr><th> </th><th>Total/Averages</th>" .
        "<th>%s</th><th>%.1f</th><th>%.1f</th>" .
        "<th class='phto'>%s</th><th class='phto'>%.1f</th><th class='phto'>%.1f</th>" .
        "<th class='phsv'>%s</th><th class='phsv'>%.1f</th><th class='phsv'>%.1f</th>" .
        "<th class='phma'>%s</th><th class='phma'>%.1f</th><th class='phma'>%.1f</th>" .
        "<th class='phff'>%s</th><th class='phff'>%.1f</th><th class='phff'>%.1f</th>" .
        "<th class='phfa'>%s</th><th class='phfa'>%.1f</th><th class='phfa'>%.1f</th>" .
        "<th class='phds'>%s</th><th class='phds'>%.1f</th><th class='phds'>%.1f</th>" .
        "<th class='phsq'>%s</th><th class='phsq'>%.1f</th><th class='phsq'>%.1f</th>" .
        "</tr>",
    $tcount,
    mydiv($tperim, $tcount) / 1000.0,
    mydiv($tpoly, $tcount) / 1000000.0,
    $totals["TO_cnt"],
    mydiv($totals["TO_perim"], $counts["TO"]) / 1000.0,
    mydiv($totals["TO_area"], $counts["TO"]) / 1000000.0,
    $totals["SV_cnt"],
    mydiv($totals["SV_perim"], $counts["SV"]) / 1000.0,
    mydiv($totals["SV_area"], $counts["SV"]) / 1000000.0,
    $totals["MA_cnt"],
    mydiv($totals["MA_perim"], $counts["MA"]) / 1000.0,
    mydiv($totals["MA_area"], $counts["MA"]) / 1000000.0,
    $totals["FF_cnt"],
    mydiv($totals["FF_perim"], $counts["FF"]) / 1000.0,
    mydiv($totals["FF_area"], $counts["FF"]) / 1000000.0,
    $totals["FA_cnt"],
    mydiv($totals["FA_perim"], $counts["FA"]) / 1000.0,
    mydiv($totals["FA_area"], $counts["FA"]) / 1000000.0,
    $totals["DS_cnt"],
    mydiv($totals["DS_perim"], $counts["DS"]) / 1000.0,
    mydiv($totals["DS_area"], $counts["DS"]) / 1000000.0,
    $totals["SQ_cnt"],
    mydiv($totals["SQ_perim"], $counts["SQ"]) / 1000.0,
    mydiv($totals["SQ_area"], $counts["SQ"]) / 1000000.0
);

$table .= "</tbody></table>";

$y1select = yearSelect(2002, $syear, "syear");
$m1select = monthSelect($smonth, "smonth");
$d1select = daySelect($sday, "sday");
$h1select = hour24Select($shour, "shour");
$y2select = yearSelect(2002, $eyear, "eyear");
$m2select = monthSelect($emonth, "emonth");
$d2select = daySelect($eday, "eday");
$h2select = hour24Select($ehour, "ehour");

/* BEGIN OUTPUT! */
$t->content = <<<EOM
<h3>Storm Based Warning Geometry Statistics</h3>

<p>Pick a time period of your choice and get back a summary table of
storm based warning polygon statistics. You should be able to highlight 
this table and paste it into Excel, if you wish.  Please note that prior to
formal implementation of Storm Based Warnings, the polygons were not the official 
warning and so their shape may not have been accurately representing the threat.
<br /><strong>Note:</strong>  Areal flood warning polygons have only been issued
since summer of 2007.
<br /><strong>Perimeter values are in kilometers and area values in square kilometers.</strong>
<br /><b>Links:</b> <a class="btn btn-info" href="{$gis_url}">Download shapefile of these warnings</a> - 
<a class="btn btn-info" href="sbwsum.phtml">View visual summaries</a></p>


<form method="GET" name="a21234">
<table cellpadding="3" class="table table-striped">
<thead class="sticky">
 <tr><td></td><th>Year</th><th>Month</th><th>Day</th><th>Hour</th><td></td></tr>
</thead>
<tbody>
 <tr><td>Start:</td>
  <td>{$y1select}</td>
  <td>{$m1select}</td>
  <td>{$d1select}</td>
  <td>{$h1select}</td>
  <td><input type='submit' value='Generate Stats'></td>
 <tr><td>End:</td>
  <td>{$y2select}</td>
  <td>{$m2select}</td>
  <td>{$d2select}</td>
  <td>{$h2select}</td>
  <td></td>
 </tr>
</tbody>
</table>
</form>


{$table}
EOM;
$t->render('full.phtml');
