package MpmasMarketSet;
use MpmasMarket;

our @ISA = qw(MpmasInputfileSet);

sub class_of_files{
	return "MpmasMarket";
 }
sub filename {
	return "MarketSet";
}
sub determine_files {
	my $self = shift;
	my $tabprices;
	if ($self->config_entry("MULTIPERIOD") and $self->config_entry("PERIODS_PER_YEAR") == 1) {

        if (defined $self->config_entry("PRICES")) {
			$tabprices = $self->config_entry("PRICES")->transform($self->get_dbh(), 3);
    		#print STDERR "Error: Missing PRICES [MPMAS TABLES]\n" and exit(1) unless (defined $self->config_entry("PRICES"));
		    
			    
			    
		    if (ref $tabprices eq "IndexedTable") {
		    
		        unless ($tabprices->is_as_expected({numCols => 4, header => [undef, "market", "year", "price"] })) {
			        
			        $tabprices->printme_with_header();
			        print STDERR "Error: The PRICES table does not have the expected format.\nFour columns expected (item, market, year, price)\n";
			        exit(1);
		        }
		    }
		    elsif (ref $tabprices eq "MpmasQl3EqnElements::mpmasTableCollection")  {

		          for my $t ($tabprices->list_of_subtable_names) {
		            unless ($tabprices->get_subtable($t)->is_as_expected({numCols => 4, header => [undef, "market", "year", "price"] })) {
			        
			            $tabprices->get_subtable($t)->printme_with_header();
			            print STDERR "Error: The PRICES table $t does not have the expected format.\nFour columns expected (item, market, year, price)\n";
			            exit(1);
		            }  
		          
		          }  
		    
		    }
		    else {
		            print STDERR "Error: The PRICES table as an unexpected PERL class:".ref($tabprices) ."\n";
			        exit(1);
		    }
			    
	    }
	    else {
		       	$tabprices = IndexedTable->create_empty(3, "PRICES", ["item", "market", "year", "price"]);
	    }
		$self->set_config_entry("CONVERTED_PRICES", $tabprices);
    }
        
   if (defined $tabprices and ref ($tabprices) eq "MpmasQl3EqnElements::mpmasTableCollection")  { 	
        for my $t ($tabprices->list_of_subtable_names) {

	        for my $p (0..$self->config_entry("MARKETS") - 1) {
	            my $suffix = $t;
	            $suffix =~ s/^PRICES_//;
		        my $fname;
		        if ($suffix =~ /^_*$/) { #In case all are empty use default file name
    		           $fname = sprintf("%01d", $p );
		        }
		        else {
		            $fname = sprintf("%01d_%s", $p, $suffix );
		        }
		        $self->add_file($p."_".$t,$fname);
	        }
        }
   }
   else {
	    for my $p (0..$self->config_entry("MARKETS") - 1) {
		    my $fname = sprintf("%01d", $p);
		    $self->add_file($p,$fname);
	    }
   }
}

sub prepare_shared_files {
	my $self = $_[0];
	if ($self->config_entry("MULTIPERIOD")) {
		
		if ($self->config_entry("PERIODS_PER_YEAR") == 1) {
    		my $tabprices = $self->config_entry("CONVERTED_PRICES");
			
			my @items;
			if (ref $tabprices eq "IndexedTable") {
			 	@items = $tabprices->query([],0);
    			@items = sort {$a cmp $b} @items;			 	
			} 
			elsif (ref $tabprices eq "MpmasQl3EqnElements::mpmasTableCollection")  {
				my $check = 0;
    			my $firstT;

			    for my $t ($tabprices->list_of_subtable_names) {
       			    my @temp = $tabprices->get_subtable($t)->query([],0);
			        unless ($check) { ##read item list from first table
                        @items = @temp;
                     	@items = sort {$a cmp $b} @items;
                        $firstT = $t;
                        $check++;
                    }
                    else {
                        #check that all subtables contain the same items to catch likely errors and avoid incompatibilities with the MIP inserters. Otherwise SCENARIOS should be used.
                        if (scalar @items != scalar @temp) {
                            print STDERR "Error: The PRICES table $t does not have the same number of items (", scalar @temp , ") as the table $firstT (",scalar @items,").\nMake sure all items appear in all tables.\n";
					        exit(1);
				        }
				        @temp = sort {$a cmp $b} @temp;
				        for my $i (0..$#items) {
				            unless ($items[$i] eq $temp[$i]) {
				                print STDERR "Error: The PRICES table $t does not contain the same items as the table $firstT.\n",$items[$i], " vs " , $temp[$i],"\nMake sure all items appear in all tables.\n";
					            exit(1);
				            }
				        
				        }
                    }
                        
			    }
			}

			my %itemIDs ;
			for my $i (0..$#items) {
				$itemIDs{$items[$i]} = $i;
			}

			$self->set_config_entry("PRICE_ITEM_LOOKUP", \%itemIDs);
			$self->set_config_entry("PRICE_ITEMS_SORTED", \@items);
		}
		else {
			print STDERR "Error: Missing PRICES_PERIODS [MPMAS TABLES]\n" and exit(1) unless (defined $self->config_entry("PRICES_PERIODS"));
		   
			my $tabprices = $self->config_entry("PRICES_PERIODS")->transform($self->get_dbh(), 4);
			my @items = $tabprices->query([],0);
			@items = sort {$a cmp $b} @items;
			my %itemIDs ;
			for my $i (0..$#items) {
				$itemIDs{$items[$i]} = $i;
			}
			$self->set_config_entry("CONVERTED_PRICES_PERIODS", $tabprices);
			$self->set_config_entry("PRICE_ITEM_LOOKUP", \%itemIDs);
			$self->set_config_entry("PRICE_ITEMS_SORTED", \@items);


		}
	
		if (defined $self->config_entry("INITIAL_PRICE_EXPECTATIONS")) {
			my $expprices = $self->config_entry("INITIAL_PRICE_EXPECTATIONS")->transform($self->get_dbh(), 2);
			
				unless ($expprices->is_as_expected({numCols => 3, header => [undef, "market", "price"] })) {	
					$expprices->printme_with_header();
					print STDERR "Error: the INITIAL_PRICE_EXPECTATIONS table does not have the expected format.\nThree columns expected (item, market, price)\n";
					exit(1);
				}
			$self->set_config_entry("CONVERTED_PRICE_EXPECTATIONS", $expprices);
		}
	}
}

sub prepare_special_files {
	my $self = $_[0];
	for my $f ($self->files) {
		$f->prepare_special();
	}
}
