package MpmasInputBlock;

use strict;
use warnings;
use Exporter;
use Storable qw(dclone);
use Data::Dumper;
use SimpleObject;
our @ISA = qw(SimpleObject);


sub new {
	my ($class, $cc, $priority) = @_;
	my $self = {};
	$self->{commentary_columns} = $cc;
	$self->{priority} =  $priority;
	$self->{Rows} = [];
	$self->{id} = "N/A";
	bless $self, $class;
	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) = @_;
	my $hash = {( row => \@row, type => 0)};
	push @{ $self->{Rows}} , $hash;
}

sub add_comment_row {
	my ($self, @row) = @_;
	my $hash = { row => \@row, type => 1};
	push @{ $self->{Rows}} , $hash;
}

sub add_commentonly_row {
	my ($self, @row) = @_;
	my $hash = {( row => \@row, type => 2)};
	push @{ $self->{Rows}} , $hash;
}
sub add_noncomment_row {
	my ($self, @row) = @_;
	my $hash = {( row => \@row, type => 3)};
	push @{ $self->{Rows}} , $hash;
}
sub add_noncommentonly_row {
	my ($self, @row) = @_;
	my $hash = {( row => \@row, type => 4)};
	push @{ $self->{Rows}} , $hash;
}
sub add_empty_rows {
	my ($self,$n) = @_;
	for (1..$n) {
		push @{ $self->{Rows} }, {(row=> [("")], type => 0)};
	}
}
sub add_table {
	my ($self, $arrayref) = @_;
	for my $i (@$arrayref){
		push @{ $self->{Rows} }, {(row=> $i, type => 0)};
	}
}
sub add_row_at_beginning {
	my ($self, @row) = @_;
	unshift @{ $self->{Rows} }, {(row => \@row, type => 0)};
}
sub write {
	#writes 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;
	
	unless ($commentmode) {
	    $s = $self->{commentary_columns} ;
	    foreach (1 .. $s) { $leftmargin .=  "\t" } 
	}
	
	for my $r ( @{ $self->{Rows} } ) {
		$i++;
		print $out "\n" and next if ( not $commentmode and $r->{type} == 1 );
		next if ( not $commentmode and $r->{type} == 2 );
		print $out "\n" and next if ($commentmode and $r->{type} == 3 );
		next if ($commentmode and $r->{type} == 4 );

		do { 
			no warnings 'uninitialized';
			print $out $leftmargin , join ("\t", @{$r->{row}}[$s..$#{$r->{row}}] ), "\n";
		};
	}
}

1;
