<& /htmlheader &>

<& modelheader &>
% my $sm_str = ", $sm" || '';
<h2>Nonsynthetic Tracklets, <% $min_dets %>+ Detections<% $sm_str %></h2>
<h3>TJD <% $nn + 1 - 50000 %> (MOPS Night Number <% $nn %>)<br>
<% $utdate_str %>
</h3>
<!-- <h3>Available Survey Modes<br>
% my %seen = (); foreach my $sm (sort { $a cmp $b } grep { !$seen{$_}++ } @survey_modes_found) {
<a href="<% qq{?nn=$nn&sort=$sort&maxv=$maxv&minv=$minv&sm=$smesc&min_dets=$min_dets} %>"><% $sm %></a><br>
% }
</h3>
-->

<!-- <% $sql %> -->
<!-- <% $found %> -->

<& stamp_pager, rooturi => "?nn=$nn&sort=$sort&maxv=$maxv&minv=$minv&sm=$smesc&min_dets=$min_dets", limit => $limit, offset => $offset, found => $found, nostamp => $nostamp &>

<form style="display: inline" action="submit_batch" target="_blank" id="myform" method="POST">
<input type=submit value="Submit Batch">
<a href="#" onclick='$("#myform").checkCheckboxes(":not(#mastercheck)")'>Check All</a> |
<a href="#" onclick='$("#myform").unCheckCheckboxes(":not(#mastercheck)")'>Uncheck All</a>

<table border=1 cellspacing=0 cellpadding=2 width="95%">
<tr>
    <th class="darkheader"> Tracklet ID </th>
    <th class="darkheader"> digest2 <br>
        <a href="<% qq{?limit=100&nn=$nn&sort=d&found=$found&maxv=$maxv&minv=$minv&sm=$smesc&min_dets=$min_dets} %>">Sort</a>
    </th>
    <th class="darkheader"> Source Chunk </th>
    <th class="darkheader"> V<sub>tot</sub> (deg/day)<br>
        <a href="<% qq{?limit=100&nn=$nn&sort=v&found=$found&maxv=$maxv&minv=$minv&sm=$smesc&min_dets=$min_dets} %>">Sort</a>
    </th>
    <th class="darkheader"> Pos Ang (deg)<br>
        <a href="<% qq{?limit=100&nn=$nn&sort=p&found=$found&maxv=$maxv&minv=$minv&sm=$smesc&min_dets=$min_dets} %>">Sort</a>
    </th>
    <th class="darkheader"> GCR<br>(arcsec) </th>
    <th class="darkheader"> Known As </th>
    <th class="darkheader"> Known q<br>
        <a href="<% qq{?limit=100&nn=$nn&sort=q&found=$found&maxv=$maxv&minv=$minv&sm=$smesc&min_dets=$min_dets} %>">Sort</a>
    </th>
    <th class="darkheader"> Submission<br>Status </th>
    <th class="darkheader"> Stamps </th>
</tr>
<tr>
% foreach $href (@rows) {
% my $trkId = $href->{tracklet_id};
<td align="center"> 
    <span class="L18bold"><% $trkId %></a></span><br>
    <a target="_blank" href="tracklet?tid=<% $trkId %>">Review</a>
</td>

<td valign="center" align="center"> 
<span class="L14bold"><% sprintf "%.1f", $href->{digest} %></span>
</td>

<td valign="center" align="center"> <% $href->{survey_mode} %> </td>

<td valign="center" align="center"> <% sprintf "%.3f", $href->{v_tot} %> </td>
<td valign="center" align="center"> <% sprintf "%.1f", $href->{pos_ang_deg} %> </td>
<td valign="center" align="center"> <% sprintf "%.2f", $href->{gcr_arcsec} %> </td>
<td valign="center" align="center"> <& /mpc_link, desig => $href->{known_name} &> </td>
<td <% ($href->{q} && $href->{q} <= 1.3) ? 'style="background:red"' : '' %> align="center"> <% $href->{q} ? sprintf("%.2f", $href->{q}) : 'N/A' %> </td>

<td valign="center" align="center">
% $substh->execute($dbname, $trkId) or die $substh->errstr; my @foo = $substh->fetchrow_array();
% if (@foo) {
<a target="_blank" href="/czar/manage_neo.html?desig=<% $foo[1] %>"><% $foo[2] || $foo[1] %></a>
% } else {
%   if (!exists($OUTREACH_MAP{$href->{fpa_id}})) {
%     if ($href->{digest} < $MPC_DIGEST_THRESHOLD || $href->{known_name}) {
<input type="checkbox" name="tracklet" value="T<% $trkId %>" <% defined($href->{q}) ? 'checked' : '' %>>
%     } else {
<input type="checkbox" name="neotracklet" value="T<% $trkId %>" <% defined($href->{q}) ? 'checked' : '' %>>
%     }
%   } else {
OUTREACH
%   }
% }
</td>

% if ($nostamp) {
<td align="center"> 
    Hidden
% } else {
<td>
% my $det = modcd_retrieve($inst, detId => $trkId);
    <& stamp4_td, size => 64, dets => [$det], short => 1 &>
% }
</td>
</tr>
% }
</table>
<input type=submit value="Submit Batch">
<a href="#" onclick='$("#myform").checkCheckboxes(":not(#mastercheck)")'>Check All</a> |
<a href="#" onclick='$("#myform").unCheckCheckboxes(":not(#mastercheck)")'>Uncheck All</a>
</form>
<p>

<& stamp_pager, rooturi => "?nn=$nn&sort=$sort&maxv=$maxv&minv=$minv&sm=$smesc&min_dets=$min_dets", limit => $limit, offset => $offset, found => $found, nostamp => $nostamp &>

<& /htmlfooter &>

<%args>
$nn
$fieldId
$limit => 100
$sort => 'd'       # 'd', 'v', 'q', 'p' allowed (digest, velocity, q, posang)
$offset => 0
$found => undef
$minv => 0
$maxv => 20
$min_dets => 3
$sm => 'nomd'           # survey mode to czar
$nostamp => undef      # set to show no postage stamps
$minra => undef
$maxra => undef
$mindec => undef
$maxdec => undef
</%args>

<%init>
use URI::Escape;
use Astro::Time;
use PS::MOPS::DC::Orbit;
use PS::MOPS::Lib qw(:all);
use PS::MOPS::Constants qw(:all);
use PS::MOPS::DC::Field;
use PS::MOPS::DC::Detection;
use PS::MOPS::DC::Tracklet;
use PS::MOPS::DC::Known;


my $MPC_DIGEST_THRESHOLD = 30;  # NEO digest threshold

# XXX LD Put IASC outreach exposure names here.
#    o5674g0313o 
#    o5674g0329o 
#    o5674g0346o 
#    o5674g0362o 
my @OUTREACH_LIST = qw(
o5681g0281o
o5681g0301o
o5681g0321o
o5681g0341o
);
my %OUTREACH_MAP;
foreach (@OUTREACH_LIST) {
    $OUTREACH_MAP{$_} = 1;
}

# If $offset and $inc are defined, use them for the mysql query.
# Otherwise use $limit, then as a last resort, all of em.
my $limit_str = '';
my $sort_str = '';
my $found_str = '';

if (defined($offset)) {
    $limit = 100 unless $limit;
    $limit_str = sprintf 'limit %d,%d', $offset, $limit;
}
else {
    $limit_str = $limit ? "limit $limit" : '';
}

if ($sort eq 'q') {
    $sort_str = 'order by if(q is null,999,q)';
}
elsif ($sort eq 'v') {
    $sort_str = 'order by v_tot desc';
}
elsif ($sort eq 'va') {
    $sort_str = 'order by v_tot';
}
elsif ($sort eq 'p') {
    $sort_str = 'order by pos_ang_deg';
}
else {
    $sort_str = 'order by digest desc, v_tot desc';
}


my $survey_mode_str = '';
if ($sm =~ /^MD/) {
    $survey_mode_str = "and (f.survey_mode like '$sm%')";
}
elsif ($sm ne 'nomd') {
    $survey_mode_str = "and (f.survey_mode like '%$sm%')";
}
else {
    $survey_mode_str = "and (not f.survey_mode like 'MD%')";
}
my $smesc = uri_escape($sm);
    
my $utdate_str = mopslib_mjd2utctimestr($nn + 1);
$utdate_str =~ s/T.*//; # trim everything after date
$utdate_str .= 'UT';

if (!defined($found)) {
    $found_str = 'SQL_CALC_FOUND_ROWS';
}

my $inst = $m->notes('INST');
my $dbname = $inst->dbname;
my $model = $m->notes('MODEL');
my $dbh = $inst->dbh();

my $substh = $dbh->prepare(<<"SQL") or die $dbh->errstr;
select disposition, desig, mpc_desig from export.mpc_sub where dbname=? and tracklet_id=? limit 1
SQL

my $vsel;
if ($sm =~ /^MD/) {
    # Medium deep, respect slow movers
    $vsel = "(t.digest > 0 and v_tot > $minv)";
}
else {
    # 3PI, SS, want high scorers regardless of velocity.
    $vsel = "((t.digest > 0 and v_tot > $minv) or (t.digest > 50))";
}

my $and = '';
if ($minra) {
    $and = "and (d.ra_deg between $minra and $maxra) and (d.dec_deg between $mindec and $maxdec)";
}

my $sql = <<"SQL";
select $found_str
    d.det_id tracklet_id,
    1 digest,
    1 v_tot,
    1 pos_ang_deg,
    1 gcr_arcsec,
    1 q,
    'foo' known_name,
    f.se_deg sol_elong,
    f.eb_deg ecl_lat,
    f.survey_mode,
    f.fpa_id
from fields f
    join detections d using(field_id)
where f.nn = $nn and field_id=$fieldId
$and
$sort_str
$limit_str
SQL
my $sth = $dbh->prepare($sql) or die $dbh->errstr;
$sth->execute() or die $sth->errstr;

my @rows;
my $href;
while ($href = $sth->fetchrow_hashref()) {
    push @rows, $href;
}
$sth->finish();

if ($found_str) {
    ($found) = $dbh->selectrow_array("select FOUND_ROWS()");
}

# Make a list of survey modes used.
my @survey_modes_found = map { $_->[0] } modcf_retrieveSurveyModes($inst, nn => $nn);
s/^\d+\.\w+\.\w\.// foreach @survey_modes_found;
s/\.[PQ][12]$// foreach @survey_modes_found;
</%init>
