#!/usr/bin/env perl

# Process all DOs for export for a given MOPS DB.
#
# @par USAGE
#
# process-dos-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-dos-all.pl {DB_NAME}\n";
    exit;
}
our $inst=PS::MOPS::DC::Instance->new(DBNAME=>$g_DBNAME);
our $mops_logger=$inst->getLogger;

# Get all DOs
# @param none
# @return none
sub process_dos {
    my $sql="select derivedobject_id from derivedobjects order by derivedobject_id";
    my $dbh=$inst->dbh();
    my $sth=$dbh->prepare($sql);
    $sth->execute();
    my $result=$sth->fetchall_arrayref();

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

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

        # Insert export detections.
        my $mops_detections;

        if(is_exportable($inst,$do_id)){
            $mops_detections=get_mops_detections($inst, $do_id);
            insert_detections_for_export($inst, $do_id, $mops_detections);
        }
    }
    $mops_logger->info("MPC-EXPORT: Processed $cnt DOs.");
}

# @todo Verify existence of necessary export database structures.

print "All DOs 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 DOs in DB $g_DBNAME.");
my $start=new Benchmark;
process_dos();
my $end=new Benchmark;
$mops_logger->info("MPC-EXPORT: time: process-dos-all: " . timestr(timediff($end,$start),'all'));
