#!/usr/bin/env perl

# Insert serialized MOPS objects into a MOPS Instance.

use strict;
use Storable;
use PS::MOPS::DC::Tracklet;
use PS::MOPS::DC::Field;
use PS::MOPS::DC::Orbit;
use PS::MOPS::DC::DerivedObject;
use PS::MOPS::DC::Instance;

my $INST=PS::MOPS::DC::Instance->new(DBNAME=>$ENV{MOPS_DBINSTANCE});

if($#ARGV+1!=2){
    die "Usage: program {detections file} {orbits file}";
}

print "Processing dets:$ARGV[0] and orbits:$ARGV[1].\n";


my $DET_FILE=$ARGV[0];
my $ORBIT_FILE=$ARGV[1];

my %TRACKLETS;

my $detection_sets_ref=retrieve("$DET_FILE");
my $orbits_ref=retrieve("$ORBIT_FILE");

$|=1;

my $field=modcf_retrieve($INST,fieldId=>1);
if(!$field){
    die "Not able to retrieve field.";
}

print "Inserting detections.\n";
print "Creating tracklets and inserting detections and tracklets.\n";

$INST->pushAutocommit(0);

my $tracklet;
my $cnt=0;
while((my $k, my $v)=each %{$detection_sets_ref}){

    # Iterate over each detection in each set.
    foreach my $d (@{$v}){
        $d->{_inst}=$INST;

        # Set additional attributes that were not set during detection creation.
        $d->{filter}="DD";
        $d->{isSynthetic}=0;

        $d->addToField($field);
    }

    # Create a single tracklet for each set of detections.
    $tracklet=PS::MOPS::DC::Tracklet->new($INST,
                                          detections=>$v,
                                          classification=>'C') || die "Cannot create tracklet";
    $tracklet->{fieldId}=1;
    $tracklet->insert();
    print ".";
    push(@{$TRACKLETS{$k}},$tracklet); # Push the tracklet into an array in the TRACKLETS hash.
    $cnt++;
}

$INST->dbh->commit();

print "\n";

orbits:

my $cnt=0;

print "Inserting orbits.\n";
print "Creating derived objects and inserting derived objects.\n";

my $orbit_id;
my $mpc_name;

$INST->pushAutocommit(0);

# Load orbits.
while((my $k, my $v)=each %{$orbits_ref}){
    $v->{_inst}=$INST;
    $orbit_id=$v->insert(); # Insert the orbit.

    # Create a derived object associated with the orbit.
    my $DO=PS::MOPS::DC::DerivedObject->new();
    $DO->{_inst}=$INST;
    $DO->{orbitId}=$v->{orbitId};
    $DO->{objectName}=$k;
    $DO->{longName}=$k;
    $DO->insert();

    $DO->attributeTracklets(TRACKLETS_AREF=>\@{$TRACKLETS{$k}});

    print "." if $cnt % 10 == 0;
}

$INST->dbh->commit();

print "\n";

print "Finished.\n";
