package MpmasInputBlockImmediate;

use strict;
use warnings;
use Exporter;
use Storable qw(dclone);
use Data::Dumper;
use SimpleObject;
use File::Temp qw /tempfile/;
use File::Util::Tempdir qw(get_user_tempdir);
use File::Path;

use Carp qw/croak/;
our @ISA = qw(SimpleObject);

my $instance_counter = 0;
my $tempfilepath = "/tmp/mpmasql/blocks";
my $tempfilestub = "mpmasqlInputBlock";
my $tempfileext = ".tmp";

sub set_tempfilepath_base {
    $tempfilepath = $_[1];
}


sub new {
	my ($class, $cc, $priority, $skip_comments) = @_;
	$skip_comments = 0 unless (defined $skip_comments);
	

	
	my $self = {};
	bless $self, $class;

	$self->{id} = ++$instance_counter;
	$self->{commentary_columns} = $cc;
	$self->{priority} =  $priority;
	$self->{skip_comments} =  $skip_comments;
	#$self->{tempfile} = $tempfilepath.$tempfilestub . $self->{id} . $tempfileext;
	#$self->{comfile} = $tempfilepath.$tempfilestub ."COM". $self->{id} . $tempfileext;
	
	$self->{Rows} = [];
	

	if ($^O eq "MSWin32") {
		$tempfilepath = get_user_tempdir."\\mpmasql\\blocks";
		&mkpath($tempfilepath);
	}
	elsif ($^O eq "linux") {
		&mkpath($tempfilepath);
	} 
	else {
		&mkpath($tempfilepath);
	}
	
	my ($fh, $fh2);
	
	($fh, $self->{tempfile}) = tempfile($tempfilestub."XXXXXX", DIR=> $tempfilepath, UNLINK=>1);
	($fh2, $self->{comfile}) = tempfile($tempfilestub."COMXXXXXX", DIR=> $tempfilepath, UNLINK=>1) unless( $skip_comments);
	
	
	#open ($fh, ">", $self->{tempfile}) or (croak( "Error in MpmasInputBlockImmediate: Could not open ".$self->{tempfile}."\n"));
	#open ($fh2, ">", $self->{comfile}) or (croak( "Error in MpmasInputBlockImmediate: Could not open ".$self->{comfile}."\n"));
	
	$self->{open} = 1;
	
	$self->{filehandle} = $fh;
	$self->{comhandle} = $fh2;

	return $self;
}


sub set_priority {
	my ($self, $set) = @_;
	$self->{priority} = $set if (defined $set);
	return $self->{priority};
}
sub priority {
    return $_[0]->{priority};
}

sub commentary_columns {
	return $_[0]->{commentary_columns};
}
sub set_commentary_columns {
	$_[0]->{commentary_columns} = $_[1] if (defined $_[1]);
}

sub add_row {
	my ($self, @row) = @_;
	croak("MpmasInputBlockImmediate already closed\n") unless ($self->{open} == 1);
	no warnings 'uninitialized';
	print {$self->{filehandle}}	join("\t", @row[$self->{commentary_columns} .. $#row ] ),"\n";
	unless ($self->{skip_comments}) {
		print {$self->{comhandle}}	join("\t", @row[0 .. $self->{commentary_columns} -1 ] ),"\n" ;
		push @{ $self->{Rows}} , 0;
	}
}

sub add_comment_row {
	my ($self, @row) = @_;
	no warnings 'uninitialized';
	croak("MpmasInputBlockImmediate already closed\n") unless ($self->{open} == 1);
	print { $self->{filehandle}	} "\n";
	unless ($self->{skip_comments}) {
		print  { $self->{comhandle}	} join("\t", @row),"\n";
		push @{ $self->{Rows}} ,1;
	}
}

sub add_commentonly_row {
	my ($self, @row) = @_;
	no warnings 'uninitialized';
	croak("MpmasInputBlockImmediate already closed\n") unless ($self->{open} == 1);
	unless ($self->{skip_comments}) {
		print {$self->{comhandle} }	join("\t", @row),"\n";
		push @{ $self->{Rows}} , 2;
	}
}
sub add_noncomment_row {
	my ($self, @row) = @_;
	no warnings 'uninitialized';
	croak("MpmasInputBlockImmediate already closed\n") unless ($self->{open} == 1);
	print {$self->{filehandle}}	join("\t", @row),"\n";	
	unless ($self->{skip_comments}) {
		print {$self->{comhandle}}	"\n" ;
		push @{ $self->{Rows}} , 3;
	}
}
sub add_noncommentonly_row {
	my ($self, @row) = @_;
	croak("MpmasInputBlockImmediate already closed\n") unless ($self->{open} == 1);
	print {$self->{filehandle}}	join("\t", @row),"\n";	
	unless ($self->{skip_comments}) {
		push @{ $self->{Rows}} , 4;
	}
}
sub add_empty_rows {
	my ($self,$n) = @_;
	no warnings 'uninitialized';
	croak("MpmasInputBlockImmediate already closed\n") unless ($self->{open} == 1);
	for (1..$n) {
		print {$self->{filehandle} }	"\n";
		unless ($self->{skip_comments}) {
			print {$self->{comhandle} }	"\n" ;
			push @{ $self->{Rows} }, 0;
		}
	}
}
sub add_table {
	my ($self, $arrayref) = @_;
	croak("MpmasInputBlockImmediate already closed\n") unless ($self->{open} == 1);
	no warnings 'uninitialized';
	for my $row (@$arrayref){
		print {$self->{filehandle}}	join("\t", @{$row}[$self->{commentary_columns} .. $#{$row} ] ),"\n";
		print {$self->{comhandle}}	join("\t", @{$row}[0 .. $self->{commentary_columns} -1 ] ),"\n" unless ($self->{skip_comments});
	}
}

sub add_column {
	my ($self, $text) = @_;
	croak("MpmasInputBlockImmediate already closed\n") unless ($self->{open} == 1);
	no warnings 'uninitialized';
	print {$self->{filehandle}}	 "\t", $text ;
	#print {$self->{comhandle}}	join("\t", @row[0 .. $self->{commentary_columns} -1 ] ),"\n";
	
}
sub end_row {
	my ($self) = @_;
	croak("MpmasInputBlockImmediate already closed\n") unless ($self->{open} == 1);
	no warnings 'uninitialized';
	print {$self->{filehandle}}	 "\n" ;
	#print {$self->{comhandle}}	join("\t", @row[0 .. $self->{commentary_columns} -1 ] ),"\n";
	unless ($self->{skip_comments}) {
		push @{ $self->{Rows}} , 0 ;
	}
}



sub write {
	#appends prepared InputBlock to specified file skipping specified number of columns if not in DBG mode
	#arguments (filehandle, DBG mode, extra empty columns at left margin)
	my ($self, $out, $commentmode, $leftmargin) = @_;
        
	my $i = -1;
	my $s = 0;
	
	if(	$self->{open}) {
		$self->{open} = 0;
		close($self->{filehandle});
		close($self->{comhandle}) unless ($self->{skip_comments});
	}
	
	unless ($commentmode) {
		
		
	    $s = $self->{commentary_columns} ;
	    foreach (1 .. $s) { $leftmargin .=  "\t" } 

		my $fin; 
		open ($fin, "<", $self->{tempfile} ) or croak("Error in MpmasInputBlockImmediate->write()\n: Could not open tempfile\n");
	    
		while ( <$fin> ) {			
				no warnings 'uninitialized';
				print $out $leftmargin ,$_;
		}
	    close ($fin);
	    
	}
	elsif (! $self->{skip_comments})  {
		my ($fin, $cin); 
		open ($fin, "<", $self->{tempfile} ) or croak("Error in MpmasInputBlockImmediate->write()\n: Could not open tempfile\n");
	    open ($cin, "<", $self->{comfile} ) or croak("Error in MpmasInputBlockImmediate->write()\n: Could not open comments tempfile\n");
		
			
		for my $r ( @{ $self->{Rows} } ) {
			$i++;
			my $comtext = "";
			my $rowtext = "\n";
			if ($r == 1 ) { #comment row
				$comtext = <$cin>;
				$rowtext = <$fin>;
				 $rowtext = "\n"
			}
			if ($r == 2) { #comment only row
				$comtext = <$cin>;
			}
			elsif ($r == 3) { #non-comment row
				$rowtext = <$fin>;
				$comtext = <$cin>;
				$comtext = "";
			}
			elsif ($r == 4) { #non-comment only row
				$rowtext = <$fin>;
			}
			else {
				$comtext = <$cin>;
				chomp($comtext); #remove final "\n"
				$rowtext = <$fin>;
			}

			do { 
				no warnings 'uninitialized';
				print $out $leftmargin, $comtext, $rowtext;
			};
		}
		close($fin);
		close($cin);
	}
}

1;
