<?php
// Frontend for dynamic windrose generation.  All kinds of options exist in
// this form and are basically translated into /cgi-bin/mywindrose.py, which
// then translates into pyIEM.windrose_utils
require_once "../../config/settings.inc.php";
require_once "../../include/database.inc.php";
require_once "../../include/forms.php";
require_once "../../include/myview.php";

// Makes sure this page has proper context
require_once "../../include/sites.php";
$ctx = get_sites_context();
$station = $ctx->station;
$network = $ctx->network;
$metadata = $ctx->metadata;


// Switch this page to DCP, if necessary
if (strpos($network, "COOP") > 0) {
    $dbconn = iemdb("mesosite");
    $stname = iem_pg_prepare(
        $dbconn,
        "SELECT network from stations where id = $1 and network = $2",
    );
    $rs = pg_execute(
        $dbconn,
        $stname,
        Array(
            $station,
            str_replace("_COOP", "_DCP", $network),
        )
    );
    if (pg_num_rows($rs) == 1){
        $res = pg_fetch_row($rs);
        $network = $res[0];
        header("Location: /sites/dyn_windrose.phtml?station={$station}&network={$network}");
        die();
    }

}

// HTTP GET vars
$day1 = get_int404("day1", 1);
$day2 = get_int404("day2", date("d"));
$month1 = get_int404("month1", 1);
$month2 = get_int404("month2", date("m"));
$year1 = get_int404("year1", date("Y"));
$year2 = get_int404("year2", date("Y"));
$hour1 = get_int404("hour1", 0);
$hour2 = get_int404("hour2", 0);
$minute1 = get_int404("minute1", 0);
$minute2 = get_int404("minute2", 0);
$units = isset($_GET["units"]) ? xssafe($_GET["units"]) : "mph";
$nsector = get_int404('nsector', 36);
$staticrange = get_int404('staticrange', 0);
$level = isset($_GET["level"]) ? floatval($_GET['level']) : 1000;
$fmt = isset($_GET["fmt"]) ? xssafe($_GET["fmt"]) : 'png';
$conv = isset($_GET["conv"]) ? xssafe($_GET["conv"]) : "from";
$dpi = get_int404("dpi", 100);
$bins = array(2, 5, 7, 10, 15, 20);
function conv($val){
    if (trim($val) == ""){
        return "";
    }
    return floatval($val);
}
for ($i = 0; $i < sizeof($bins); $i++) {
    $bins[$i] = isset($_GET["bin{$i}"]) ? conv(xssafe($_GET["bin{$i}"])) : $bins[$i];
}

// If hour1 is set, we might as well assume we are wanting a plot
if (isset($_GET["hour1"])) {
    $rose_uri = "/cgi-bin/mywindrose.py?nsector=$nsector&amp;station=$station" .
        "&amp;network=$network&amp;day1=$day1&amp;day2=$day2&amp;" .
        "month1=$month1&amp;month2=$month2&amp;year1=$year1&amp;year2=" .
        "$year2&amp;hour1=$hour1&amp;" .
        "hour2=$hour2&amp;minute1=$minute1&amp;minute2=$minute2&amp;" .
        "units=$units&amp;fmt=$fmt&amp;dpi=$dpi&amp;conv=$conv";
    if (isset($_GET["setbins"])) {
        $rose_uri .= sprintf("&amp;bins=%s", implode(",", $bins));
    }
    if (isset($_GET["hourlimit"])) {
        $rose_uri .= "&amp;hourlimit=1";
    }
    if (isset($_GET["monthlimit"])) {
        $rose_uri .= "&amp;monthlimit=1";
    }
    if (isset($_GET["limit_by_doy"])) {
        $rose_uri .= "&amp;limit_by_doy=1";
    }
    if (isset($_GET["hourrangelimit"])) {
        $rose_uri .= "&amp;hourrangelimit=1";
    }
    if ($staticrange > 1 && $staticrange < 101) {
        $rose_uri .= "&amp;staticrange={$staticrange}";
    }
    if ($network == 'RAOB') {
        $rose_uri .= "&amp;level=" . $level;
    }
    $rosedata_uri = "{$rose_uri}&amp;justdata=true";
}

$firstyear = 1995;
if (!is_null($metadata["archive_begin"])) {
    $firstyear = $metadata["archive_begin"]->format("Y");
}

$t = new MyView();
$t->iemselect2 = true;
$t->title = "Custom Wind Roses";
$t->sites_current = "custom_windrose";
$tznote = "(Times are in {$metadata["tzname"]} time zone)";
if ($network == 'RAOB') {
    $tznote = "(Times presented are in UTC)";
}

$ar = array(
    "png" => "PNG Image (.PNG)",
    "pdf" => "Portable Document Format (.PDF)",
    "svg" => "Scalable Vector Graphic (.SVG)"
);
$fselect = make_select("fmt", $fmt, $ar);

$content = <<<EOM
<h3>Custom Wind Rose Plots</h3>

This application attempts to generate a wind rose for a time period of
your choice.  Please be patient when submitting this form, as it may take
up to a few minutes to generate the plot due to the large amount of data
that this application processes. You can limit the dataset from which the
windrose is derived in three ways:
<ol>
 <li>By only including observations from a specific hour</li>
 <li>By only including observations from a specific month or by a specific
 period of dates each year.</li>
 <li>By only including observations between a start and end hour</li>
</ol>

<p>You can also, optionally, prescribe six wind speed bins, in the units of
your choice.  The first bin from zero to your value is assumed to be calm values.
The last bin represents the last value to infinity.
These images and data are in the public domain,
the <a href="/disclaimer.php">disclaimer page</a> contains more details.</p>

<p><a href="/cgi-bin/mywindrose.py?help" class="btn btn-primary">
<i class="bi bi-file-earmark-text"></i> Backend Documentation
</a>
exists for those that wish to script against the windrose image/data service.
Additionally, <a href="/plotting/auto/?q=16" class="btn btn-primary">
<i class="bi bi-graph-up"></i> Autoplot 16</a> allows for custom wind roses
based on thresholds being met.</p>

<form method="GET" name="windrose">
<input type="hidden" name="station" value="{$station}">
<input type="hidden" name="network" value="{$network}">

<h4>Select Start/End Time:</h4>
<i>{$tznote}</i>

<table class="table table-bordered">
  <tr>
    <td></td>
    <th>Year</th><th>Month</th><th>Day</th>
    <th>Hour</th><th>Minute</th>
<td rowspan="3">
EOM;
$hs1 = hourSelect($hour1, "hour1");
$hs2 = hourSelect($hour2, "hour2");
$mi1 = minuteSelect($minute1, "minute1");
$mi2 = minuteSelect($minute2, "minute2");
if ($network == 'RAOB') {
    $levels = array(
        1000 => 1000,
        925 => 925,
        850 => 850,
        700 => 700,
        500 => 500,
        400 => 400,
        300 => 300,
        250 => 250,
        150 => 150,
        100 => 100
    );
    $content .= 'Select Pressure Level: ' . make_select("level", $level, $levels) . ' hPa<br />';
    $hours = array(0 => 0, 12 => 12);
    $hs1 = make_select("hour1", $hour1, $hours);
    $hs2 = make_select("hour2", $hour2, $hours);
    $mi1 = "";
    $mi2 = "";
}
$ar = array(
    "kts" => "knots (KTS)",
    "mph" => "miles per hour (MPH)",
    "mps" => "meters per second (MPS)"
);
$uselect = make_select("units", $units, $ar);

$content .= '<input type="checkbox" name="hourlimit" value="1" ';
if (isset($_GET["hourlimit"])) $content .= "checked=\"checked\" ";
$content .= 'id="r1"> <label for="r1">1. Limit to Hour of Start Time</label>';

$content .= '<br /><input type="checkbox" name="monthlimit" value="1" ';
if (isset($_GET["monthlimit"])) $content .= "checked=\"checked\" ";
$content .= 'id="r2"> <label for="r2">2a. Limit to Month of Start Time</label>';

$content .= '<br /><input type="checkbox" name="limit_by_doy" value="1" ';
if (isset($_GET["limit_by_doy"])) $content .= "checked=\"checked\" ";
$content .= 'id="r2b"> <label for="r2b">2b. Limit to Month+Day Period each Year</label>';

$content .= '<br /><input type="checkbox" name="hourrangelimit" value="1" ';
if (isset($_GET["hourrangelimit"])) $content .= "checked=\"checked\" ";
$content .= 'id="r3"> <label for="r3">3. Limit to Range of hours given by start and end time</label>';

$content .= <<<EOM
<br />
<input type="number" step=".1" min="0" max="100" name="staticrange" value="{$staticrange}" size="3"
 id="staticrange">
<label for="staticrange">Specify frequency axis maximum (number between 1 and 100)
(0 represents auto-scale) (units are percent).</label>
EOM;

// Allow setting of wind speed bins
$missive = <<<EOM
<p>Since calm winds have no direction, the first bin lumps all the calm
reports together. A value of 2 knots is likely the most appropriate here. The
bin ranges are inclusive on the lower end and exclusive on the upper end. If you
want to plot less than six bins, leave the right most boxes blank.</p>
EOM;
$content .= sprintf(
    '<br /><input type="checkbox" name="setbins" ' .
        'value="1"%s id="o2"> <label for="o2">Optional. User provided wind speed bins</label><br />' .
        '<div style="display: %s;" id="showbins"> 0 - ' .
        '<input type="text" name="bin0" value="%s" size="4"> - ' .
        '<input type="text" name="bin1" value="%s" size="4"> - ' .
        '<input type="text" name="bin2" value="%s" size="4"> - ' .
        '<input type="text" name="bin3" value="%s" size="4"> - ' .
        '<input type="text" name="bin4" value="%s" size="4"> - ' .
        '<input type="text" name="bin5" value="%s" size="4"> +' .
        '%s' .
        '</div>',
    isset($_GET["setbins"]) ? " checked=\"checked\"" : "",
    isset($_GET["setbins"]) ? "block" : "none",
    $bins[0],
    $bins[1],
    $bins[2],
    $bins[3],
    $bins[4],
    $bins[5],
    $missive,
);

$content .= "<br /><strong>Bar Convention of Plot:</strong>";
$content .= '<br /><input type="radio" id="met" name="conv" value="from"';
$content .= ($conv == "from") ? ' checked="checked"' : "";
$content .= '><label for="met"> Meteorology: Bars point in direction wind is '.
    'blowing from.</label>';
$content .= '<br /><input type="radio" id="eng" name="conv" value="to"';
$content .= ($conv == "to") ? ' checked="checked"' : "";
$content .= '><label for="eng"> Engineering: Bars point in direction wind is '.
    'blowing toward.</label>';

// Pick between display units
$content .= '<br />Display Units: ';
$content .= $uselect;

$content .= '<br />Direction Bins: <select name="nsector">';
$opts = array(8, 12, 16, 20, 24, 28, 32, 36);
foreach ($opts as $k => $v) {
    $content .= sprintf(
        "<option value=\"%s\" %s>%s</option>\n",
        $v,
        ($nsector == $v) ? 'selected="selected"' : '',
        $v
    );
}


$content .= '
</select>

<br />Image Format: ' . $fselect . '
<br />Image DPI: <input type="text" name="dpi" value="' . $dpi . '" size="4">
<br /><input type="submit"></td>
  </tr>

  <tr>
    <th>Start:</th>
    <td>
     ' . yearSelect($firstyear, $year1, "year1") . '
    </td>
    <td>
     ' . monthSelect($month1, "month1") . '
    </td>
    <td>
     ' . daySelect($day1, "day1") . '
    </td>
    <td>
     ' . $hs1 . '
    </td>
    <td>
     ' . $mi1 . '
    </td>
  </tr>

  <tr>
    <th>End:</th>
    <td>' . yearSelect($firstyear, $year2, "year2") . '</td>
    <td>
     ' . monthSelect($month2, "month2") . '
    </td>
    <td>
     ' . daySelect($day2, "day2") . '
    </td>
    <td>
     ' . $hs2 . '
    </td>
    <td>
     ' . $mi2 . '
    </td>
  </tr>
</table>
</form>';

if (isset($rose_uri)) {
    $content .= "<div class=\"alert alert-info\" id=\"img-loading\">Image will appear below once generated, please be patient...</div>";
    $content .= "<a href='{$rosedata_uri}' class='btn btn-primary' role='button' rel='nofollow'><i class='bi bi-list'></i> View raw data for chart</a><br />";
    if ($fmt == 'pdf') {
        $content .= <<<EOM
<object id="windrose-plot" src="{$rose_uri}" width="700px" height="700px">
    <embed src="{$rose_uri}" width="700px" height="700px">
    </embed>
</object>
EOM;
    } else {
        $content .= "<img src=\"$rose_uri\" class=\"img-fluid\" id=\"windrose-plot\">";
    }
} else {
    $content .= "<div class=\"alert alert-info\">Please make your custom plot
          selections above</a>";
}
$t->jsextra = <<<EOM
<script src="dyn_windrose.module.js" type="module"></script>
EOM;

$t->content = $content;
$t->render('sites.phtml');
