#!/usr/bin/env perl

use warnings;
use strict;

## report the program and machine
use Sys::Hostname;
my $host = hostname();
print "\n\n";
print "Starting script $0 on $host\n\n";

use vars qw( $VERSION );
$VERSION = '0.01';

use IPC::Cmd 0.36 qw( can_run run );
use PS::IPP::Metadata::Config;
use PS::IPP::Metadata::Stats;
use PS::IPP::Metadata::List qw( parse_md_list );
use File::Temp qw( tempfile );

use PS::IPP::Config qw($PS_EXIT_SUCCESS
		       $PS_EXIT_UNKNOWN_ERROR
		       $PS_EXIT_SYS_ERROR
		       $PS_EXIT_CONFIG_ERROR
		       $PS_EXIT_PROG_ERROR
		       $PS_EXIT_DATA_ERROR
		       $PS_EXIT_TIMEOUT_ERROR
		       metadataLookupStr
		       caturi
		       );
my $ipprc = PS::IPP::Config->new(); # IPP configuration
use File::Spec;

use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );

my ($warp_id, $camera, $dbname, $workdir, $no_update, $no_op);
GetOptions(
    'warp_id|i=s'       => \$warp_id, # Warp identifier
    'camera|c=s'        => \$camera, # Camera name
    'dbname|d=s'        => \$dbname, # Database name
    'workdir|w=s'       => \$workdir, # Working directory, for output files
    'no-update'         => \$no_update,	# Don't update the database?
    'no-op'             => \$no_op, # Don't do any operations
) or pod2usage( 2 );

pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
pod2usage(
    -msg => "Required options: --warp_id --camera",
    -exitval => 3,
) unless defined $warp_id
    and defined $camera;

$ipprc->define_camera($camera);

# Look for programs we need
my $missing_tools;
my $warptool = can_run('warptool') or (warn "Can't find warptool" and $missing_tools = 1);
my $dvoImageOverlaps = can_run('dvoImageOverlaps') or (warn "Can't find dvoImageOverlaps" and $missing_tools = 1);
my $dvoImageExtract = can_run('dvoImageExtract') or (warn "Can't find dvoImageExtract" and $missing_tools = 1);
if ($missing_tools) { 
    warn("Can't find required tools.");
    exit($PS_EXIT_CONFIG_ERROR); 
}

# Get list of component imfiles for exposure
my $imfiles;
{
    my $command = "$warptool -imfile -warp_id $warp_id";
    $command .= " -dbname $dbname" if defined $dbname;
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => 1);
    unless ($success) {
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	&my_die("Unable to perform warptool -imfile: $error_code", $warp_id, $error_code);
    }

    my $mdcParser = PS::IPP::Metadata::Config->new;	# Parser for metadata config files
    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
	&my_die("Unable to parse metadata config doc", $warp_id, $PS_EXIT_PROG_ERROR);
    $imfiles = parse_md_list($metadata) or 
	&my_die("Unable to parse metadata list", $warp_id, $PS_EXIT_PROG_ERROR);
}

# Determine the imfile/skycell overlaps
my @overlaps = ();

unless ($no_op) {
    # Calculate the overlaps between imfiles and skycells

    my $tessellations = $ipprc->tessellations(); # Hash of defined tessellations
    foreach my $tess_id ( keys %$tessellations ) {
	### Because DVO doesn't use psModules, it doesn't understand Nebulous --- check
	my ($scheme) = $$tessellations{$tess_id} =~ m|^(\S+):|; # The scheme, e.g., file://, path://
	if (defined $scheme and lc($scheme) eq 'neb') {
	    &my_die("Tessellation $tess_id refers to a Nebulous path: $$tessellations{$tess_id}", $warp_id, $PS_EXIT_CONFIG_ERROR);
	}
	
	my $tess_dir = $ipprc->convert_filename_absolute( $$tessellations{$tess_id} ); # Catdir for DVO
	print STDERR "tessellation: $tess_id, $tess_dir\n";

	my $imfile = $imfiles->[0];
	my $camRoot = $imfile->{cam_path_base};
	my $psastroFile = $ipprc->filename("PSASTRO.OUTPUT.MEF", $camRoot); # MEF psastro output
	
	my @dirlist = File::Spec->splitdir( $psastroFile );
	my $psastroRootFile = pop @dirlist;
	print STDERR "psastroRootFile: $psastroRootFile\n";
	
	# run the dvoImageOverlaps program to get the overlaps with this image 
	my $command = "$dvoImageOverlaps -D CATDIR $tess_dir " . $ipprc->file_resolve($psastroFile);
	my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	    run(command => $command, verbose => 1);
	unless ($success) {
	    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	    &my_die("Unable to perform dvoImageOverlaps: $error_code", $warp_id, $error_code);
	}
	my @matchlist = split ('\n', (join "", @$stdout_buf));
	
	# The command "dvoImageOverlaps -D CATDIR tessellation (megacam)" returns:
	# 729534pa.cmf[ccd00.hdr]  :  skycell.051.fits
	# PSASTRO.OUTPUT[CMF.HEAD] : SKYCELL
	# [CMF.HEAD] is optionally used for MEF files (SIMPLE or MOSAIC)
	
	# now match the imfiles to this list
	my @unique_skycells = ();
	my %found_skycells = ();
	foreach my $imfile (@$imfiles) {
	    my $fileLevel = $imfile->{filelevel};
	    my $entry = "";
	    if (lc($fileLevel) eq "chip") {
		my $class_id = $imfile->{class_id};
		my $chipRoot = $ipprc->file_resolve( $imfile->{chip_path_base} );
		my $extname = $ipprc->extname_rule("CMF.HEAD", $class_id); # MEF psastro output
		
		print STDERR "class: $class_id, chiproot: $chipRoot, extname: $extname\n";
		
		$entry = $psastroRootFile . '\[' . $extname . '\]';
	    } else {
		$entry = "$psastroRootFile";
	    }

	    my @skycells = &select_skycells ($entry, @matchlist);
	    foreach my $skycell (@skycells) {
		my %overlap = ();
		$overlap{skycell_id} = $skycell;
		$overlap{tess_id}    = $tess_id;
		$overlap{cam_id}     = $imfile->{cam_id};
		$overlap{class_id}   = $imfile->{class_id};
		$overlap{fault}      = $imfile->{fault};
		push @overlaps, \%overlap;
		
		printf STDERR "overlap: %s : %s , %s\n", $skycell, $imfile->{cam_id}, $imfile->{class_id};
		
		# generate a unique list of the skycells
		unless ($found_skycells{$skycell}) {
		    push @unique_skycells, $skycell;
		    $found_skycells{$skycell} = 1;
		}
	    }
	}

	# Extract the skycells to images, used as warp templates.
	foreach my $skycell_id (@unique_skycells) {
	    my $skyDir = caturi($workdir, "tess_" . $tess_id, "sky_" . $skycell_id );
	    my $skyFile = $ipprc->file_prepare( $skycell_id, $skyDir );
	    unless ($ipprc->file_exists( $skyFile )) {
		my $skyFileResolved = $ipprc->file_create( $skyFile ); # Resolved filename, for Nebulous
		my $command = "$dvoImageExtract -D CATDIR $tess_dir $skycell_id -o $skyFileResolved";
		my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
		    run(command => $command, verbose => 1);
		unless ($success) {
		    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
		    &my_die("Unable to perform dvoImageExtract: $error_code", $warp_id, $error_code);
		}
	    }
	}
    }
} else {
    # create an overlap with an entry for each skycell:imfile match
    foreach my $imfile (@$imfiles) {
	my %overlap = ();
	$overlap{skycell_id} = 'default';
	$overlap{tess_id}    = 'default';
	$overlap{cam_id}     = $imfile->{cam_id};
	$overlap{class_id}   = $imfile->{class_id};
	$overlap{fault}      = $imfile->{fault};
	push @overlaps, \%overlap;
    }
}

# Generate a MDC file with the overlaps
my ($overlapFile, $overlapName) = tempfile( 'overlaps.wrp' . $warp_id . '.mdc.XXXX', UNLINK => 1 );
print $overlapFile "warpSkyCellMap MULTI\n\n";
foreach my $overlap (@overlaps) {
    print $overlapFile "warpSkyCellMap   METADATA\n";
    print $overlapFile "  warp_id        S32    $warp_id\n";
    print $overlapFile "  skycell_id     STR    $overlap->{skycell_id}\n";
    print $overlapFile "  tess_id        STR    $overlap->{tess_id}\n";
    print $overlapFile "  cam_id         S32    $overlap->{cam_id}\n";
    print $overlapFile "  class_id       STR    $overlap->{class_id}\n";
    print $overlapFile "  fault          S16    $overlap->{fault}\n";
    print $overlapFile "END\n\n";
}
close $overlapFile;

system "cat $overlapName";

# Add the processed file to the database
unless ($no_update) {
    my $command = "$warptool -addoverlap -mapfile $overlapName"; # Command to run warptool
    $command .= " -dbname $dbname" if defined $dbname;

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => 1);
    unless ($success) {
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	warn("Unable to perform warptool -addoverlap: $error_code\n");
	exit($error_code);
    }
}

sub my_die
{
    my $msg = shift;		# Warning message on die
    my $warp_id = shift;	# Warp identifier
    my $exit_code = shift;	# Exit code to add

    warn($msg);

    # No failure option on warptool for this mode, so just die.
    exit $exit_code;
}

sub select_skycells 
{
    my $entry = shift;		# File+Ext to search for
    my @list = @_;		# List of "File+Ext : skycell"

    my @skycells = ();

    foreach my $line (@list) {
	if ($line =~ m|$entry|) {
	    my ($skycell) = $line =~ m|$entry\S*\s+:\s+(\S+)|;
	    push @skycells, $skycell;
	}
    }
    @skycells;
}

END {
    my $status = $?;
    system("sync") == 0
        or die "failed to execute sync: $!" ;
    $? = $status;
}

__END__
