#!/usr/bin/env perl

# Process all tracklets with known_ids for export for a given MOPS DB.
#
# @par USAGE
#
# process-trackets-all.pl {MOPS_DB_NAME}

use strict;
use warnings;

use PS::MOPS::ExportLib;
use PS::MOPS::DC::Instance;
use Getopt::Long;
use Benchmark ':hireswallclock';

my $opt_noprompt;
my $options=GetOptions("noprompt"=>\$opt_noprompt); # flag

our $g_DBNAME; # Name of database to be processed.
my $input; # User input.

if($ARGV[0]){
    $g_DBNAME=$ARGV[0];
}
else {
    print "Usage: process-tracklets-all.pl {DB_NAME}\n";
    exit;
}
our $inst=PS::MOPS::DC::Instance->new(DBNAME=>$g_DBNAME);
our $mops_logger=$inst->getLogger;

# Get all tracklets that have a known_id and that have not been previously exported.
# @param none
# @return none
sub process_tracklets {
    # Select all the tracklets that have a known ID and that have not been previously exported.
    my $sql="SELECT tracklets.tracklet_id, tracklets.known_id FROM tracklets
             WHERE tracklets.tracklet_id NOT IN (SELECT tracklet_export_id FROM export WHERE tracklet_export_id IS NOT NULL)";

    my $dbh=$inst->dbh();
    my $sth=$dbh->prepare($sql);
    $sth->execute();
    my $result=$sth->fetchall_arrayref();

    my $cnt=0; # maintain count of processed tracklets.

    # Iterate over all tracklets.
    foreach my $tracklet (@{$result}){
        $cnt++;
        my $tracklet_id=$tracklet->[0];
        print "Processing tracklet ID $tracklet_id...\n";

        # Insert export detections.
        my $mops_detections;

        # If the tracklet has a known_id and it has not been previously exported to the MPC then export it to the MPC.
        my $known_id=$tracklet->[1];
        
        # Process all the detections in the tracklet whether or not they have been previously exported.
        # The database design SHOULD prevent duplicate detection export records.
        if($known_id){
            $mops_detections=get_mops_detections_for_tracklet($inst, $tracklet_id);
            insert_detections_for_tracklet_export($inst, $tracklet_id, $mops_detections);
        }
    }
    $mops_logger->info("MPC-EXPORT: Processed $cnt tracklets.");
}

# @todo Verify existence of necessary export database structures.

print "All tracklets in MOPS DB $g_DBNAME will be processed.\n";

if(!$opt_noprompt){
    print "\nEnter to continue.";
    chomp($input=<STDIN>);
    print "\n";
}

$mops_logger->info("MPC-EXPORT: Processing tracklets in DB $g_DBNAME.");
my $start=new Benchmark;
process_tracklets();
my $end=new Benchmark;
$mops_logger->info("MPC-EXPORT: time: process-tracklets-all: " . timestr(timediff($end,$start),'all'));
