<& /htmlheader &>

<& modelheader &>
<h2>Removed Nonsynthetic Derived Objects</h2>
% if ($nn) {
	<h3>MOPS Night Number <% $nn %> (TJD <% $nn + 1 %>)<br>
	<% mopslib_mjd2utctimestr($nn) %> to <% mopslib_mjd2utctimestr($nn + 1) %>
	</h3>
% } else {
	<h3>MOPS OC Number <% $ocnum %></h3>
%}
<!-- <% $sql %> -->
<!-- <% $found %> -->

<& /lib/pager, rooturi => "?ocnum=$ocnum&nn=$nn&sort=$sort", limit => $limit, offset => $offset, found => $found &>
</br></br>
<form style="display: inline" action="restore_derived_object.html" target="_blank" id="DerivedObjs" method="POST">
<input type=submit value="Restore Derived Objects">
<table border=1 cellspacing=0 cellpadding=2 width="90%">
<tr>
    <th class="darkheader"> MOPS Internal<br>Object Name </th>
    <th class="darkheader"> a (AU)<br>
        <a href="?limit=100&ocnum=<% $ocnum %>&nn=<% $nn %>&sort=a&found=<% $found %>">Sort</a>
    </th>
    <th class="darkheader"> q (AU)<br>
        <a href="?limit=100&ocnum=<% $ocnum %>&nn=<% $nn %>&sort=q&found=<% $found %>">Sort</a>
    </th>
    <th class="darkheader"> e <br>
        <a href="?limit=100&ocnum=<% $ocnum %>&nn=<% $nn %>&sort=e&found=<% $found %>">Sort</a>
    </th>
    <th class="darkheader"> i (deg) </th>
    <th class="darkheader"> RMS Residual<br>(arcsec) </th>
    <th class="darkheader"> Arc Length<br>(days) </th>
    <th class="darkheader"> Known As </th>
    <th class="darkheader"> Restore </th>
    <th class="darkheader"> Stamps </th>
</tr>
<tr>
% foreach $href (@rows) {
% my $objectName = $href->{object_name};
% my $dobj = modcdo_retrieve($inst, derivedobjectId => $href->{dobj_id});
<td align="center"> <span class="L14bold"><a target="_blank" href="search?id=<% $objectName %>"><% $objectName %></a></span><br>
</td>
<td align="center"> <% $href->{e} < 1 ? sprintf "%.6f", $href->{q} / (1 - $href->{e}) : 'N/A' %> </td>
<td align="center"> <% sprintf "%.6f", $href->{q} %> </td>
<td align="center"> <% sprintf "%.3f", $href->{e} %> </td>
<td align="center"> <% sprintf "%.3f", $href->{i} %> </td>
<td align="center"> <% sprintf "%.3f", $href->{residual} %> </td>
<td align="center"> <% sprintf "%.1f", $href->{arc_length_days} %> </td>
<td align="center"> <% unilinkify(split /,/, $href->{known_as}) %> </td>
<td align="center"><input type="checkbox" name="derivedObj" value="<% $href->{dobj_id} %>" id="<% $href->{dobj_id} %>" autocomplete="off"></td>
<td> 

<!-- table for stamps -->
<table border=0 cellpadding=2 cellspacing=0>
<tr>
% foreach my $trk ($dobj->fetchTracklets()) {
% my $f = modcf_retrieve($inst, fieldId => $trk->fieldId);
% my $date_str = mopslib_mjd2utctimestr($trk->extEpoch);
% $date_str =~ s/T.*//g;    # trim time part of date string
<td> 
    <& stampmini, dets => $trk->detections, size => 48 &><br>
    <% $date_str %><br>
    <% $f->surveyMode %><br>
</td>
% }
</tr>
</table>

</td>
</tr>
% }
</table>
<input type=submit value="Restore Derived Objects">
</form>
</br></br></br>
<& /lib/pager, rooturi => "?ocnum=$ocnum&nn=$nn&sort=$sort", limit => $limit, offset => $offset, found => $found &>

<& /htmlfooter &>

<%args>
$nn => undef
$ocnum => undef
$limit => 100
$sort => 'q'       # 'q', 'a', 'e' allowed
$offset => 0
$found => undef
</%args>

<%init>
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::DerivedObject;

# 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 = '';

# Restrict query results to those that fall within the specified range
# $offset specifies the starting point of the range and $limit specifies
# the number of records to retrieve.
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 the result set by semi-major axis of the orbit.
    $sort_str = 'order by o.q'
}
elsif ($sort eq 'e') {
	# Sort the result set by the eccentricity of the orbit.
    $sort_str = 'order by o.e';
}
elsif ($sort eq 'a') {
	# Sort the result set by semi-major axis divided by (1-eccentricity)
    $sort_str = 'order by if(o.e>1,1000,o.q/(1-o.e))';
}

if (!defined($found)) {
	# Clause that records the number of rows that would be returned without the limit clause.
    $found_str = 'SQL_CALC_FOUND_ROWS';
}

# Create select statement to retrieve derived objects.
my $inst = $m->notes('INST');
my $model = $m->notes('MODEL');
my $dbh = $inst->dbh();
my $where = $nn ? "f.nn = $nn" : "f.ocnum = $ocnum";
my $sql = <<"SQL";
select $found_str
    do.derivedobject_id dobj_id,     
    do.object_name object_name,     
    o.q q,     
    o.e e,     
    o.i i,     
    o.residual residual,     
    o.arc_length_days arc_length_days,     
    group_concat(k.known_name) known_as
from fields f     
    join history h using(field_id)     
    join derivedobjects do using(derivedobject_id)     
    join orbits o on do.orbit_id=o.orbit_id     
    join derivedobject_attrib doa on do.derivedobject_id=doa.derivedobject_id     
    join tracklets t using(tracklet_id)     
    left join known k using(known_id) 
where $where
    and h.classification='N' 
    and h.event_type='D' 
    and o.e < 1
    and do.status = '$DERIVEDOBJECT_STATUS_KILLED'
group by do.derivedobject_id
$sort_str
$limit_str
SQL

my $sth = $dbh->prepare($sql) or die $dbh->errstr;
$sth->execute() or die $sth->errstr;

my @rows;	# Stores all rows retrieved.
my $href;
while ($href = $sth->fetchrow_hashref()) {
    push @rows, $href;
}
$sth->finish();

# Get number of derived objects retrieved.
if ($found_str) {
    ($found) = $dbh->selectrow_array("select FOUND_ROWS()");
}


sub unilinkify {
    # Given a list of known object names, return a string containing
    # a uniqified list and links to the MPC for each object.
    my @names = @_;
    my %map = map { $_ => 1 } @names;
    my $rename;
    my @unique;
    foreach my $name (sort keys %map) {  
        $name =~ s/^\s+|\s+$//g;
        $name =~ s/^([12]\d\d\d)([A-Z]+)/$1 $2/;      # convert e.g. 2004MN4 => 2004 MN 4
        $rename = $name;
        $rename =~ s/ +/+/g;
        $rename =~ s/[()]//g;
        push @unique, qq{<a target="_blank" href="http://www.minorplanetcenter.net/db_search/show_object?object_id=$rename&commit=Show">$name</a><br>};
    }
    return join '', @unique;
}

</%init>
