package MpmasSimulationRunParameterScens;

use strict;
use warnings;
use Exporter;
use Storable qw(dclone);
use Data::Dumper;
use MpmasInputfile;
use MpmasInputBlock;
use MpmasInputBlockImmediate;
use IndexedTable;
use CtUtilities qw(numbers_robust_to_sorting);

use Cwd;
our @ISA = qw(MpmasInputfile);

sub filename {
	"SimrunParameterScens";
}

sub required {
	my ($self) = @_;
	return ($self->config_entry("MULTIPERIOD")); 
}


sub prepare_special {
    my ($self, $paramscendef, $Nsimrunparams, $strictlySorted, $checkComplete ) = @_;
    
    
    my $NumRow = $self->milpinfo("NumRow");
	my $NumCol = $self->milpinfo("NumCol");
	my $numMilps = scalar @{ $self->milplist };
    
    my $block;
    
    my @sorted_paramScens =  sort {numbers_robust_to_sorting($a) cmp numbers_robust_to_sorting($b)} $paramscendef->query([],0);
	if ( ($Nsimrunparams * scalar( @sorted_paramScens)  > $self->config_entry("LIMIT_FOR_IMMEDIATE")  /2 /$numMilps )
		|| ( $NumRow   > $self->config_entry("LIMIT_FOR_IMMEDIATE")   /$numMilps ) 
		|| ( $NumCol   > $self->config_entry("LIMIT_FOR_IMMEDIATE")   /$numMilps ) 
		) {
		$block  = MpmasInputBlockImmediate->new(2,10, $self->get_skip_comments());
	}
	else {
    	$block = MpmasInputBlock->new(2,10);
    }


    my %check_seen;

	for my $s ( @sorted_paramScens)#scenarios
	{
	   for my $k ( $strictlySorted ?  
	                (   sort {numbers_robust_to_sorting($a)  cmp numbers_robust_to_sorting($b)} $paramscendef->query([$s],0) ) : 
	                    $paramscendef->query([$s],0)
	                )#parameters
	   {
	        my $v = $paramscendef->query([$s,$k], 3 );
	        
	        $v =~ s/^"//; #remove surrounding quotes if any
	        $v =~ s/"$//;
			$block->add_row("", "", $s, $k, $v);
			#print $s, ":", $k,":", $v, "\n";
			if ($checkComplete && exists $MpmasQLRegistry::mpmas_simrun_variation{$k}) {
			    $check_seen{$k}{$s} = 1;
			}
			
		}

	}
	$self->add_block($block);
    if ($checkComplete) {
	    for my $k (keys %check_seen) {
	        for my $s ( $paramscendef->query([],0) ) {
	            unless (exists  $check_seen{$k}{$s}) {
	            
	                print STDERR "Warning: You have set predefined run-specific parameter $k for some parameter variations scenarios, but not for $s. Be sure this was done on purpose!\n";
	            }
	        }
        }
    }
}
1;
