#!/usr/bin/perl -w

package ippToPsps::StackBatch;

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(
            "ST",   # type 
            $_[2],  # camera
            $_[3],  # gpc1Db
            $_[4],  # ippToPspsDb
            $_[5],  # path
            $_[6],  # datastore
            0,  # expId
            "NULL",  # expName
            $_[7],  # dvoDb
            $_[8],  # dvoPath
            "ThreePi", # distGroup TODO
            $_[9], # dontTarBall
            $_[10], # verbose
            $_[11]  # save_temps
            );
    
    $self->setProgram("stackbatch");

    $self->{_skyId} = $_[1]; 

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

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

  # TODO hardcode demo file for now
#        print $inputFile "/data/ippc18.0/home/rhenders/psphotstack.v3.001.cmf\n";
 #   print $inputFile "/data/ipp053.0/eugene/psps.20110221/staticsky/MD04.V2/skycell.124/MD04.V2.skycell.124.stk.228.000.cmf\n";


 print $inputFile "/data/ipp053.0/eugene/md04.20110320/staticsky/MD04.V2/skycell.087/MD04.V2.skycell.087.stk.280.000.cmf";
            return 1;

    my ($nebPath, $numInputs);
    if (!$self->{_gpc1Db}->getStackStageCmfs($self->{_skyId}, \$nebPath, \$numInputs)){

        print "* No cmf files found for this skyId ($self->{_skyId})\n"; 
        return 0;
    }
    # loop round all cmf files
    my $i;
    for ($i = 0; $i<$numInputs; $i++) {

        # get real filename from neb 'key' TODO neater exit
        my $fpaObjects = $self->{_ipprc}->filename("PSPHOT.STACK.OUTPUT",$nebPath, $i) or last;
        my $cmf = $self->{_ipprc}->file_resolve($fpaObjects) or return 0;

        print $inputFile $cmf . "\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 .= " -skyid $self->{_skyId}";

    # 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;

