<& /htmlheader, title => (sprintf "%s TJD %d, %d-%d", $submitter, ($nn + 1 - 50000), $offset + 1, $offset + $limit) &>

<& modelheader &>
<h2>Submitted tracklets by user <% $submitter %></h2>
<h3> <a href="<% qq{?submitter=$submitter&nn=$nn} %>">All</a> | <a href="<% qq{?submitter=$submitter&nn=$nn&known=n} %>">Unknown</a> |  <a href="<% qq{?submitter=$submitter&nn=$nn&known=n&pairs=1} %>">Unknown Pairs</a> </h3>
<h3>TJD <% $nn + 1 - 50000 %> (MOPS Night Number <% $nn %>)<br>
<% $utdate_str %>
</h3>

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

<& stamp_pager, rooturi => "?nn=$nn&sort=$sort&submitter=$submitter&known=$known&pairs=$pairs", 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" valign="top"> Tracklet ID </th>
    <th class="darkheader" valign="top"> digest2 <br>
        <a href="<% qq{?limit=100&nn=$nn&sort=d&found=$found&submitter=$submitter&known=$known&pairs=$pairs} %>">Sort</a>
    </th>
    <th class="darkheader" valign="top"> Source Chunk </th>
    <th class="darkheader" valign="top"> V<sub>tot</sub> (deg/day)<br>
        <a href="<% qq{?limit=100&nn=$nn&sort=v&found=$found&submitter=$submitter&known=$known&pairs=$pairs} %>">Sort</a>
    </th>
    <th class="darkheader" valign="top"> Apparent Mag (V) </th>
    <th class="darkheader" valign="top"> Pos Ang (deg)<br>
        <a href="<% qq{?limit=100&nn=$nn&sort=p&found=$found&submitter=$submitter&known=$known&pairs=$pairs} %>">Sort</a>
    </th>
    <th class="darkheader" valign="top"> Known As </th>
    <th class="darkheader" valign="top"> Known q<br>
    <th class="darkheader" valign="top"> GCR (arcsec)<br>
        <a href="<% qq{?limit=100&nn=$nn&sort=g&found=$found&submitter=$submitter&known=$known&pairs=$pairs} %>">Sort</a>
    </th>
    <th class="darkheader" valign="top"> Probability<br>
        <a href="<% qq{?limit=100&nn=$nn&sort=prob&found=$found&submitter=$submitter&known=$known&pairs=$pairs} %>">Sort</a>
    </th>
    <th class="darkheader" valign="top"> Submission<br>Status </th>
    <th class="darkheader" valign="top"> 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>

% my $trk = modct_retrieve($inst, trackletId => $trkId);
<td valign="center" align="center"> <% sprintf "%.3f &deg;/day", $href->{v_tot} %> </td>
<td valign="center" align="center"> <% sprintf "%.1f V", $href->{ext_mag} %> </td>
<td valign="center" align="center"> <% sprintf "%.1f&deg;", $href->{pos_ang_deg} %> </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"> <% sprintf "%.2f&quot;", $href->{gcr_arcsec} %><br> </td>
<td valign="center" align="center"> <% sprintf "%.2f", $href->{probability} %> </td>

<td valign="center" align="center">
% $substh->execute($dbname, $trkId) or die $substh->errstr; my @foo = $substh->fetchrow_array();
% if (@foo) {
% my ($s1, $s2) = ('', '');
%   if ($foo[0] eq 'J') { $s1 = '<strike>'; $s2 = '</strike>'; }
<% $s1 %><a target="_blank" href="/czar/manage_neo.html?desig=<% $foo[1] %>"><% $foo[2] || $foo[1] %></a><% "<br>($foo[0], $foo[3])" %><% $s2 %>
% } else {
%   if (!exists($OUTREACH_MAP{$href->{fpa_id}}) || $href->{digest} >= $MPC_DIGEST_THRESHOLD) {
%     if ($href->{known_name} && $href->{q} > $ISS_Q_THRESHOLD) {
OSS
%     }
%   } else {
OUTREACH
%   }
% }
</td>

% if ($nostamp) {
<td align="center"> 
    Hidden
% } else {
<td>
<label for="T<% $trkId %>">
% my @fakedets = map { { detId => $_ } } split /,/, $href->{det_ids};
    <& stamp4_td, size => 64, dets => \@fakedets, in_nn => $nn &>
% }
</label>
</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&submitter=$submitter&known=$known&pairs=$pairs", limit => $limit, offset => $offset, found => $found, nostamp => $nostamp &>
<hr style="visibility: hidden; clear: both; margin-top: 14px">
<& /htmlfooter &>

<%args>
$nn
$limit => 100
$sort => 'd'       # 'd', 'v', 'q', 'p', 'g', 'prob', 'sub' allowed (digest, velocity, q, posang, gcr, probability, submitted+prob)
$offset => 0
$found => undef
$nostamp => undef      # set to show no postage stamps
$field_id => undef      # single field_id
$submitter
$pairs => 0
$known => 'any'
</%args>

<%init>
use List::Util qw(sum);
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::Tracklet;
use PS::MOPS::DC::Known;


$submitter =~ s/[^\w]//g;    # clean up
#my $ISS_Q_THRESHOLD = 5.5;      # don't submit anything with known q > this
my $ISS_Q_THRESHOLD = 99;
#my $MPC_DIGEST_THRESHOLD = 50;  # NEO digest threshold
my $MPC_DIGEST_THRESHOLD = 30;  # NEO digest threshold

# XXX LD Put IASC outreach exposure names here.
my @OUTREACH_LIST = qw(
);
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 = '';
my $h_str = $pairs ? 'having count(ta.det_id)=2' : '';
my $k_str = '';
if ($known =~ /y/i) {
    $k_str = 'and t.known_id is not null';
}
elsif ($known =~ /n/i) {
    $k_str = 'and t.known_id is null';
}

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';
}
elsif ($sort eq 'g') {
    $sort_str = 'order by gcr_arcsec desc';
}
elsif ($sort eq 'prob') {
    $sort_str = 'order by probability';
}
elsif ($sort eq 'sub') {
    $sort_str = 'order by if(known_id is null, 0, 1) desc, probability desc';
}
else {
#    $sort_str = 'order by digest desc, v_tot desc';
    $sort_str = 'order by digest desc, t.gcr_arcsec';
}


my $field_sel = '';
if ($field_id) {
    $field_sel = "and field_id=$field_id";
}


my $utdate_str = mopslib_mjd2utctimestr($nn + 1);
$utdate_str =~ s/T.*//; # trim everything after date
$utdate_str .= 'UT';

my $prob_str = '';

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, submitter from export.mpc_sub where dbname=? and tracklet_id=? limit 1
SQL

my $sql = <<"SQL";
select $found_str
    t.tracklet_id tracklet_id,
    group_concat(ta.det_id) det_ids,
    t.digest digest,
    t.v_tot v_tot,
    t.ext_mag ext_mag,
    t.pos_ang_deg pos_ang_deg,
    t.gcr_arcsec gcr_arcsec,
    t.probability probability,
    k.q q,
    k.known_name known_name,
    f.se_deg sol_elong,
    f.eb_deg ecl_lat,
    f.survey_mode,
    f.fpa_id
from fields f
    join tracklets t ignore index(classification) using(field_id)
    join tracklet_attrib ta using(tracklet_id)
    left join known k using(known_id)
    join export.mpc_sub em
where f.nn = $nn and t.classification='N' 
and em.dbname='$dbname' and em.tracklet_id=t.tracklet_id and em.det_id=ta.det_id
and em.submitter='$submitter'
$k_str
$field_sel
group by t.tracklet_id
$h_str
$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()");
}

sub _avg {
    my (@vals) = @_;
    if (@_) {
        return sum(@_) / @_;
    }
    return 0;
}
</%init>
