#!/usr/bin/perl -w

package ippToPsps::InitBatch;

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 new {
    my ($class) = @_;

    # Call the constructor of the parent class
    my $self = $class->SUPER::create(
            "IN",      # type 
            $_[1],     # camera
            undef,     # gpc1Db
            $_[2],     # ippToPspsDb
            $_[3],     # path
            $_[4],     # datastore
            0,         # expId
            "NULL",    # expName
            undef,     # dvoDb
            undef,     # dvoPath
            "ThreePi", # distGroup
            $_[5],     # dontTarball
            $_[6],     # verbose
            $_[7]);    # save_temps

    $self->setProgram("initbatch");

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

#######################################################################################
# 
# No input file necessary for IN batches 
#
#######################################################################################
sub createInputFileList {
    my ($self) = @_;

    return "NULL";
}

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

    # build command
    my $command = "$self->{program}";
    $command .= " -output $self->{_batchDir}";
    $command .= " -config ../config"; # TODO
    $command .= " -results $resultsFilePath";

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

    return $success;
}


#######################################################################################
#
# - Reads filename from results XML file
# - Updates Db
# - write 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');

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

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

    return 1;
}
1;

