#!/usr/bin/perl -w

package ippToPsps::DetectionBatch;

use warnings;
use strict;
use File::Basename;
use File::Temp qw(tempfile);
use XML::LibXML;
use IPC::Cmd 0.36 qw( can_run run );

use ippToPsps::Batch;
our @ISA = qw(ippToPsps::Batch);    # inherits from Batch class


###########################################################################
#
# Constructor (overrides superclass)
#
###########################################################################
sub existing {
    my ($class) = @_;

    # Call the constructor of the parent class
    my $self = $class->SUPER::existing(
            $_[1],  # camera
            $_[2],  # gpc1Db
            $_[3],  # batchId
            $_[4],  # ippToPspsDb
            $_[5],  # path
            $_[6],  # verbose
            $_[7]   # save_temps
            );

    bless $self, $class;
    return $self;
}


###########################################################################
#
# Constructor (overrides superclass)
#
###########################################################################
sub new {
    my ($class) = @_;

    # Call the constructor of the parent class
    my $self = $class->SUPER::create(
            "P2",   # type 
            $_[1],  # camera
            $_[2],  # gpc1Db
            $_[3],  # ippToPspsDb
            $_[4],  # path
            $_[5],  # datastore
            $_[6],  # expId
            $_[7],  # expName
            $_[8],  # dvoDb
            $_[9],  # dvoPath
            $_[10], # distGroup
            $_[11], # dontTarBall
            $_[12], # verbose
            $_[13]  # save_temps
            );

    $self->setProgram("detectionbatch");

    bless $self, $class;
    $self->process();
    return $self;
}

#######################################################################################
# 
# Locates the relevant smf file for this exposure
#
#######################################################################################
sub getSmfFile {
    my ($self) = @_;

    # get neb path of smf file
    my $nebPath = $self->{_gpc1Db}->getCameraStageSmfForThisDvoDb($self->{_dvoDb}, $self->{_expId});
    if (!$nebPath) { return undef; }

    # get real filename from neb 'key'
    my $fpaObjects = $self->{_ipprc}->filename("PSASTRO.OUTPUT",$nebPath) or return undef;

    return $self->{_ipprc}->file_resolve($fpaObjects);
}

#######################################################################################
# 
# Locates the relevant smf file for this exposure and writes the path to the file passed-in
#
#######################################################################################
sub createInputFileList {
    my ($self, $inputFile) = @_;

    my $smfFile = $self->getSmfFile();
    if (!defined $smfFile) {return 0;}

    # now write the path to this file out to temp file
    print $inputFile $smfFile . "\n";

    return 1;
}

#######################################################################################
#
# runs the ippToPsps program
#
#######################################################################################
sub runProgram {
    my ($self, $input, $resultsFilePath) = @_;

    # build command
    my $command = "$self->{program}";
    $command .= " -input $input";
    $command .= " -output $self->{_batchDir}";
    if (defined $self->{_dvoPath} ) {$command .= " -D CATDIR $self->{_dvoPath}";}
    $command .= " -config ../config"; # TODO
    $command .= " -survey $self->{_surveyType}";
    $command .= " -results $resultsFilePath";
    $command .= " -expid $self->{_expId}";
    $command .= " -expname $self->{_expName}";

    # run command
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf )
        = run(command => $command, verbose => $self->{_verbose});

    return $success;
}


#######################################################################################
#
# - Reads results from processing (min/max obj ID etc)
# - writes to Db
# - writes manifest file
#
#######################################################################################
sub parseResults {
    my ($self, $resultsFilePath) = @_;

    my($filename, $minObjId, $maxObjId, $totalDetections);

    # read results of FITS creation from XML file
    my $parser = XML::LibXML->new;
    my $doc = $parser->parse_file($resultsFilePath);
    $filename = $doc->findvalue('//filename');
    $minObjId = $doc->findvalue('//minObjID');
    $maxObjId = $doc->findvalue('//maxObjID');
    $totalDetections = $doc->findvalue('//totalDetections');

    # write results to database
    $self->{_ippToPspsDb}->setAsProcessed($self->{_batchId}, $self->{_expId}, $totalDetections, $minObjId, $maxObjId);

    # write batch manifest
    if (!$self->writeManifest($filename, $minObjId, $maxObjId)) {return 0;}

    return 1;
}
1;

