#!/home/aimpro/utils/perl64/bin/perl -I/home/aimpro/utils/site_perl/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi -I/home/aimpro/utils/perl64/site/lib
use Tk;
use Tk::LabFrame;
use Tk::LabEntry;
use subs qw/ doactive check_prelim /;
use Env qw( HOSTNAME );
use Shell qw( more );

# Main Window
$mainwind=MainWindow->new;

my $mainframe = $mainwind->Frame->pack();

# Display 16 nodes in window with appropriate buttons
# If not available grey out
my $row = 1;
my $yspace = 10;
my $xspace = 10;

# Title Label
my $mainlabel = $mainframe->Label( -text => 'CIPS Processing Interface', -fg => 'blue'  );
$mainlabel->grid(-column => 1, -row => 1, -padx => $xspace, -pady => $yspace, -columnspan => 2 );

$yspace = 5;

$row ++;
# Cal Diagnostics
my $caldiagnostics = $mainframe->Checkbutton( -text => 'Cal Diagnostics', -selectcolor => 'green', -onvalue => 'yes', -offvalue => 'no', -variable=>\$calibrationfiles );
$caldiagnostics->grid(-column => 1, -row => $row, -sticky =>'w', -padx => $xspace, -pady => $yspace );

$row ++;
my $flats = $mainframe->Checkbutton( -text => 'Flat field', -selectcolor => 'green', -onvalue => 'yes', -offvalue => 'no', -variable=>\$flatfield );
$flats->grid(-column => 1, -row => $row, -sticky =>'w', -padx => $xspace, -pady => $yspace );

my $noons = $mainframe->Checkbutton( -text => 'Noon fast cadence', -selectcolor => 'green', -onvalue => 'yes', -offvalue => 'no', -variable=>\$noonfast );
$noons->grid(-column => 2, -row => $row, -sticky =>'w', -padx => $xspace, -pady => $yspace );

$row ++;
# Level 1A
my $level1a = $mainframe->Checkbutton( -text => 'Level 1A', -selectcolor => 'green', -onvalue => 'yes', -offvalue => 'no', -variable=>\$lev1a );
$level1a->grid(-column => 1, -row => $row, -sticky =>'w', -padx => $xspace, -pady => $yspace );

# Level 1B
my $level1b = $mainframe->Checkbutton( -text => 'Level 1B', -selectcolor => 'green', -onvalue => 'yes', -offvalue => 'no', -variable=>\$lev1b );
$level1b->grid(-column => 2, -row => $row, -sticky =>'w', -padx => $xspace, -pady => $yspace );

$row ++;
# Level 2
my $level2 = $mainframe->Checkbutton( -text => 'Level 2', -selectcolor => 'green', -onvalue => 'yes', -offvalue => 'no', -variable=>\$lev2 );
$level2->grid(-column => 1, -row => $row, -sticky =>'w', -padx => $xspace, -pady => $yspace );

# Level 3
my $level3 = $mainframe->Checkbutton( -text => 'Level 3', -selectcolor => 'green', -onvalue => 'yes', -offvalue => 'no', -variable=>\$lev3 );
$level3->grid(-column => 2, -row => $row, -sticky =>'w', -padx => $xspace, -pady => $yspace );

# Start Day
$row ++;
# Date Labels
my $startlabel = $mainframe->Label( -text => 'Start Day', -fg => 'blue' );
$startlabel->grid(-column => 1, -row => $row, -padx => 1, -pady => 5, -columnspan => 1 );
my $endlabel = $mainframe->Label( -text => 'End Day', -fg => 'blue' );
$endlabel->grid(-column => 2, -row => $row, -padx => 1, -pady => 5, -columnspan => 1 );
$row ++;
my $aimstartday = $mainframe->Entry( -insertwidth => 2, -fg => 'blue', -textvariable=>\$startday );
$aimstartday->grid(-column => 1, -row => $row, -sticky =>'w', -padx => 15, -pady => 1 );
my $aimendday = $mainframe->Entry( -insertwidth => 2, -fg => 'blue', -textvariable=>\$endday );
$aimendday->grid(-column => 2, -row => $row, -sticky =>'w', -padx => 15, -pady => 1 );

# SKIP DAYS
$row ++;
my $skiplabel = $mainframe->Label( -text => 'Days to skip', -fg => 'blue' );
$skiplabel->grid(-column => 1, -row => $row, -padx => 1, -pady => 5, -columnspan => 1 );
$row ++;
my $skipday = $mainframe->Entry( -insertwidth => 2, -fg => 'blue', -textvariable=>\$skipdays );
$skipday->grid(-column => 1, -row => $row, -sticky =>'w', -padx => 15, -pady => 1 );


$row ++;
my $line1 = $mainframe->Canvas(-height => 3);
$line1->createLine( 1,1,200,1, -fill => 'black' );
$line1->grid( -column => 1, -columnspan => 2, -row => $row, -padx => $xspace, -pady => 5 );
#--------------------------------------------------------------
$row ++;
# Options Label
my $optionslabel = $mainframe->Label( -text => 'Options', -fg => 'blue' );
$optionslabel->grid(-column => 1, -row => $row, -padx => $xspace, -pady => 5, -columnspan => 2 );

$row ++;
# Preliminary
my $prelim = $mainframe->Checkbutton( -text => 'Preliminary', -selectcolor => 'green', -onvalue => 'yes', -offvalue => 'no', -variable=>\$preliminary );
$prelim->grid(-column => 1, -row => $row, -sticky =>'w', -padx => $xspace, -pady => $yspace );

# Release
my $release = $mainframe->Checkbutton( -text => 'Release', -selectcolor => 'green', -onvalue => 'yes', -offvalue => 'no', -variable=>\$definitive );
$release->grid(-column => 2, -row => $row, -sticky =>'w', -padx => $xspace, -pady => $yspace );

$row ++;
# Remove Files
my $rmfiles = $mainframe->Checkbutton( -text => 'Remove Files First', -selectcolor => 'green', -onvalue => 'yes', -offvalue => 'no', -variable=>\$remove );
$rmfiles->grid(-column => 1, -row => $row, -sticky =>'w', -padx => $xspace, -pady => $yspace );

$row ++;
# Use SCREEN
my $usescreen = $mainframe->Checkbutton( -text => 'Use screen', -selectcolor => 'green', -onvalue => 'yes', -offvalue => 'no', -variable=>\$screen );
$usescreen->grid(-column => 1, -row => $row, -sticky =>'w', -padx => $xspace, -pady => $yspace );

$row ++;
$row ++;
my $line2 = $mainframe->Canvas(-height => 3);
$line2->createLine( 1,1,200,1, -fill => 'black' );
$line2->grid( -column => 1, -columnspan => 2, -row => $row, -padx => $xspace, -pady => 1 );

#--------------------------------------------------------------

$row ++;

my $numcpus = $mainframe->Scale( -label => 'Number of CPUs', -variable=>\$num_cpus, -length => 120, -orient => 'horizontal', -to => 7, -fg => 'blue' );
$numcpus->grid(-column => 1, -row => $row, -sticky =>'w', -padx => $xspace, -pady => $yspace );


#--------------------------------------------------------------

# bind left mouse click with doactive subroutine
$level1a->bind("<Button-1>", sub{ check_level1a( $lev1a )} );
$level1b->bind("<Button-1>", sub{ check_level1b( $lev1b )} );
$level2->bind("<Button-1>", sub{ check_level2( $lev2 )} );
$level3->bind("<Button-1>", sub{ check_level3( $lev3 )} );

$prelim->bind("<Button-1>", sub{ check_prelim( $preliminary)} );
$release->bind("<Button-1>", sub{ check_release( $definitive)} );

# Start Button
$row += 2;
my $buttonstart = $mainframe->Button( -text => 'Start Processing', -borderwidth => 4, -width => 14, -fg => 'darkgreen');
$buttonstart->grid(-column => 1, -row => $row, -pady => $yspace );
$buttonstart->bind("<Button-1>", sub{ startprocessing( ) } );

# Exit Button
my $buttonexit = $mainframe->Button( -text => 'Exit',-borderwidth => 4, -width => 7, -fg => 'red', -command=>sub{exit});
$buttonexit->grid(-column => 2, -row => $row, -pady => $yspace );

# Define defaults
$prelim->select;
$release->deselect;
$level3->select;
$numcpus->set( 5 );

MainLoop;	# Starts the procedure in windows mode

sub startprocessing
{
	my $program_options = "";
	my $debuglevel = 0;
	my $num_computers = 0;
	my $debug_options = "";
	print "L1B: $lev1b\n";

	print "Starting processing of CIPS data\n";

	if( $flatfield eq 'yes' )
	{
		$program_options = $program_options.", /flatfield";
	}
	elsif( $noonfast eq 'yes' )
	{
		$program_options = $program_options.", /noon_fast_cadence";
	}
	elsif( $lev3 eq 'yes' )
	{
		$program_options = $program_options.", /level3";
	}
	elsif( $lev2 eq 'yes' )
	{
		$program_options = $program_options.", /level2";
	}
	elsif( $lev1b eq 'yes' )
	{
		$program_options = $program_options.", /just1b";
	}
	elsif( $lev1a eq 'yes' )
	{
		$program_options = $program_options.", /just1a";
	}
	else
	{
		# Message Window
		$messagewind=MainWindow->new;
		my $messageframe = $messagewind->Frame->pack();
		my $messagelabel = $messageframe->Label( -text => 'You must provide a product level!', -fg => 'red'  );
		$messagelabel->grid(-column => 1, -row => 1, -padx => 10, -pady => 10 );
		my $button2exit = $messageframe->Button( -text => 'Ok',-borderwidth => 4, -width => 7, -fg => 'red', -command=>sub{exit});
		$button2exit->grid(-column => 2, -row => 2, -pady => 5 );
	
		MainLoop;	# Starts the procedure in windows mode
	}

	if( int($skipdays) > 1 )
	{
		$program_options = $program_options.", skipday=$skipdays";
	}
	if( $calibrationfiles eq 'yes' )
	{
		$program_options = $program_options.", debug_level=7";
	}
	else
	{
		$program_options = $program_options.", debug_level=0";
	}

	if( $preliminary eq 'yes' )
	{
		$program_options = $program_options.", /prelim";
		print "Preliminary ON:\n";
	}
	
	$debug_options = $debug_options."source /aim/sds/common/scripts/setup_science_data_system.sh";
	$version = 'v4.20';

	# get the number of days to process and weither their aimdays or yd
	if( $startday > 2007001 )
	{
		$program_options = $program_options.", /yd";
		$totaldays = $endday - $startday + 1;
		print "Processing $totaldays days from $startday to $endday\n";
	}
	else
	{
		$totaldays = $endday - $startday;
		print "Processing $totaldays from $endday to $startday\n";
	}
	if( $remove eq 'yes' )
	{
		$program_options = $program_options.", /remove";
	}

	my $aimstartday = $startday;

	mkdir( sprintf( "/aim/logs/cips/%s" , $version ) );
	my $logfile = sprintf( "/aim/logs/cips/%s/%s_to_%s_cips.log" , $version, $startday, $endday);
	my $aimendday = $endday; 

	my $idl_command = "idl -e 'cips_reprocessing_idl_bridge, $aimstartday, $aimendday $program_options, cores=$num_cpus'";
	if( ($calibrationfiles eq 'yes') and ( $preliminary eq 'yes' )  )
	{
		$idl_command = "idl -e 'cips_reprocessing_idl_bridge, $aimstartday, $aimendday $program_options, /cal_files_only, cores=$num_cpus'";
	}
	$idl_command = $idl_command." | tee $logfile";
	print "Making log file $logfile\n";
	open( FH, '>', '/home/aimpro/aimcips_idl_cmd.sh' );
	print FH "#!/bin/bash\n";
	print FH "source /home/aimpro/.bash_profile\n";
	print FH "$debug_options\n";
	print FH "$idl_command\n";
	close( FH );
	system( "chmod u+x /home/aimpro/aimcips_idl_cmd.sh" );
	my $random_number = int(rand(100));

	if( $screen eq 'yes')
	{
		$systemcommand = sprintf "screen -d  -m -S \"CIPS_Reprocessing_$HOSTNAME_$random_number\" -t \"CIPS Reprocessing on $HOSTNAME\" /home/aimpro/aimcips_idl_cmd.sh";
	}
	else
	{
		$systemcommand = sprintf "xterm -geometry 180x25+1+1  -hold -T 'CIPS IDL Processing $HOSTNAME' -e /home/aimpro/aimcips_idl_cmd.sh &";
	}
	if( $num_cpus == 0 )
	{
		print "================================================================================\n";
		print "$systemcommand\n";
		more( "/home/aimpro/aimcips_idl_cmd.sh" );
		print "================================================================================\n";			
	}
	else
	{
		print "================================================================================\n";			
		print "$systemcommand\n";
		print "================================================================================\n";			
		system($systemcommand);
	}
	$aimstartday = $aimendday + 1;
}

sub check_prelim
{
	my ($e) = @_;	# Get the Node # that changed
	if( $e eq 'yes' )
	{
		$release->deselect;
	}
}
sub check_release
{
	my ($e) = @_;	# Get the Node # that changed
	if( $e eq 'yes' )
	{
		$prelim->deselect;
	}
}
sub check_manhattan
{
	my ($e) = @_;	# Get the Node # that changed
	if( $e eq 'yes' )
	{
		$currentversion->deselect;
	}
}
sub check_current
{
	my ($e) = @_;	# Get the Node # that changed
	if( $e eq 'yes' )
	{
		$manhattan_version->deselect;
	}
}

sub check_level1a
{
	my ($e) = @_;	# Get the Node # that changed
	if( $e eq 'yes' )
	{
		$caldiagnostics->deselect;
		$level1b->deselect;
		$level2->deselect;
		$level3->deselect;
	}
}
sub check_level1b
{
	my ($e) = @_;	# Get the Node # that changed
	if( $e eq 'yes' )
	{
		$caldiagnostics->deselect;
		$level1a->deselect;
		$level2->deselect;
		$level3->deselect;
	}
}
sub check_level2
{
	my ($e) = @_;	# Get the Node # that changed
	if( $e eq 'yes' )
	{
		$caldiagnostics->deselect;
		$level1a->deselect;
		$level1b->deselect;
		$level3->deselect;
	}
}
sub check_level3
{
	my ($e) = @_;	# Get the Node # that changed
	if( $e eq 'yes' )
	{
		$caldiagnostics->deselect;
		$level1a->deselect;
		$level1b->deselect;
		$level2->deselect;
	}
}
