package MpmasCropYieldsSet;

use strict;
use warnings;
use Exporter;
use Storable qw(dclone);
use Data::Dumper;
use SimpleObjectRegistry;
use MpmasInputBlock;
use SimpleObject;

our @ISA = qw(MpmasInputfileSet);
use MpmasCropYields;

sub class_of_files{
	return "MpmasCropYields";
 }
sub required {
	my $self = shift;
	return ($self->config_entry("CROP_MODEL") == 3 and $self->config_entry("BIOVERSION") == 3  );
}
sub determine_files {
	my $self = shift;
    

    my $xnyieldtab;
    my $xnyieldexp;
	if ($self->config_entry("STATICNRU") == 0 || $self->config_entry("STATICNRU") >= 2 
	        || not $self->config_entry("EXTERNALCGFORMAT0"))    {
		print STDERR "\nError: Missing EXTERNAL_CG_YIELDS [MPMAS TABLES].\nThis is required because STATICNRU has been set to 0 or >=2 or EXTERNALCGFORMAT0 is 0 \n
			and CROP_MODEL = 3 and BIOVERSION= 3\n"  and exit(1) unless (defined $self->config_entry("EXTERNAL_CG_YIELDS"));
			
		$xnyieldtab = $self->config_entry("EXTERNAL_CG_YIELDS")->transform($self->get_dbh,2);
		$self->set_global("ExternalYields", $xnyieldtab);

		if ($self->config_entry("EXO_YIELD_EXPECTATIONS")) {
			print STDERR "\nError: Missing EXTERNAL_CG_YIELD_EXPECTATIONS [MPMAS TABLES].\nThis is required because STATICNRU has been set to 0 or >=2, or EXTERNALCGFORMAT0 is zero\n
			and CROP_MODEL = 3 and BIOVERSION= 3\n and EXO_YIELD_EXPECTATIONS = 1\n"  and exit(1) unless (defined $self->config_entry("EXTERNAL_CG_YIELD_EXPECTATIONS"));
			
			$xnyieldexp = $self->config_entry("EXTERNAL_CG_YIELD_EXPECTATIONS")->transform($self->get_dbh,2);
			$self->set_global("ExternalYieldExpectations", $xnyieldexp);
		}
	}


    if (defined $xnyieldtab and ref $xnyieldtab  eq "IndexedTable"  
        and (not defined   $xnyieldexp or ref $xnyieldexp  eq "IndexedTable")  
        ) {

	    for my $y ($self->config_entry("YEAROFFIRSTHARVEST") .. $self->config_entry("ENDYEAR")) {
		    my $p = $y - $self->config_entry("YEAROFFIRSTHARVEST") + 1;
		    my $fname = sprintf("%02d", $p);
		    $self->add_file([$y],$fname);
	    }
    }
    elsif (defined $xnyieldtab and ref $xnyieldtab  eq "MpmasQl3EqnElements::mpmasTableCollection"  
            and (not defined $xnyieldexp or ref $xnyieldexp  eq "IndexedTable" )  
            ) {
            for my $t ($xnyieldtab->list_of_subtable_names) {
                my $suffix = $t;
	            $suffix =~ s/^EXTERNAL_CG_YIELDS_//;
        	    for my $y ($self->config_entry("YEAROFFIRSTHARVEST") .. $self->config_entry("ENDYEAR")) {
		            my $p = $y - $self->config_entry("YEAROFFIRSTHARVEST") + 1;
		            my $fname;
		            if ($suffix =~ /^_*$/) { #In case all are empty use default file name
        		           $fname = sprintf("%02d", $p );
		            }
		            else {
		                $fname = sprintf("%02d_%s", $p, $suffix );
		            }
		            $self->add_file([$y,$t],$fname);

	            }

              
            }
    }
    elsif (defined $xnyieldtab and ref $xnyieldtab  eq "IndexedTable"  
            and (defined   $xnyieldexp and $xnyieldexp  eq    "MpmasQl3EqnElements::mpmasTableCollection"             )  
            ) {
            for my $t ($xnyieldexp->list_of_subtable_names) {
                my $suffix = $t;
	            $suffix =~ s/^EXTERNAL_CG_YIELD_EXPECTATIONS_//;
        	    for my $y ($self->config_entry("YEAROFFIRSTHARVEST") .. $self->config_entry("ENDYEAR")) {
		            my $p = $y - $self->config_entry("YEAROFFIRSTHARVEST") + 1;
		            my $fname;
		            if ($suffix =~ /^_*$/) { #In case all are empty use default file name
        		           $fname = sprintf("%02d", $p );
		            }
		            else {
		                $fname = sprintf("%02d_Exp_%s", $p, $suffix );
		            }
      		        $self->add_file([$y,,$t],$fname);
	            }

              
            }
    }
    elsif (defined $xnyieldtab and ref $xnyieldtab  eq "MpmasQl3EqnElements::mpmasTableCollection"  
            and (defined   $xnyieldexp and ref $xnyieldexp  eq "MpmasQl3EqnElements::mpmasTableCollection"             )  
            ) {
            #print "HERE1\n";
            if ($self->config_entry("SERIES_VARIATION_ONLY_MATCHING_YIELD_EXPECTATIONS")) {
                print "HERE2\n";
                for my $t ($xnyieldtab->list_of_subtable_names) {
                   my $suffix = $t;
                   $suffix =~ s/^EXTERNAL_CG_YIELDS_//;
                   my $t2 = "EXTERNAL_CG_YIELD_EXPECTATIONS_".$suffix;
                   my $test =  $xnyieldexp->get_subtable($t2);
                    unless (defined $test) {
                        print STDERR "Error: SERIES_VARIATION_ONLY_MATCHING_YIELD_EXPECTATIONS set to 1,\nbut no matching variation of EXTERNAL_CG_YIELD_EXPECTATIONS for $t\n(Found only:", join(", ", $xnyieldexp->list_of_subtable_names())," )\nExpected $t2\n";
                        exit(1);
                    }
                


            	    for my $y ($self->config_entry("YEAROFFIRSTHARVEST") .. $self->config_entry("ENDYEAR")) {
                        my $p = $y - $self->config_entry("YEAROFFIRSTHARVEST") + 1;
                        my $fname;
                        if ($suffix =~ /^_*$/) { #In case all are empty use default file name
            		           $fname = sprintf("%02d", $p );
                        }
                        else {
                            $fname = sprintf("%02d_%s", $p, $suffix );
                        }
                        $self->add_file([$y,$t,$t2],$fname);
                        #print "CG: $fname\n";
                    }

                      
                    
                }
            }
            else {
                for my $t ($xnyieldtab->list_of_subtable_names) {
                    for my $t2 ($xnyieldexp->list_of_subtable_names) {
                        my $suffix = $t;
	                    $suffix =~ s/^EXTERNAL_CG_YIELDS_//;
	                    my $suffix2 = $t2;
        	            $suffix2 =~ s/^EXTERNAL_CG_YIELD_EXPECTATIONS_//;
	                    $suffix .= "_Exp_".$suffix2;
	                    
	                    
                	    for my $y ($self->config_entry("YEAROFFIRSTHARVEST") .. $self->config_entry("ENDYEAR")) {
		                    my $p = $y - $self->config_entry("YEAROFFIRSTHARVEST") + 1;
		                    my $fname;
		                    if ($suffix =~ /^_*Exp_*$/) { #In case all are empty use default file name
                		           $fname = sprintf("%02d", $p );
		                    }
		                    else {
		                        $fname = sprintf("%02d_%s", $p, $suffix );
		                    }
    		                $self->add_file([$y,$t,$t2],$fname);
	                    }

                      
                    }
                }
            }
    }
}
sub prepare_shared_files {
	my $self = $_[0];

}

sub prepare_special_files {
	my $self = shift;
	for my $f ($self->files) {
		
		unless ( $f->prepare_special() ) {
			if ($self->config_entry("MULTIPERIOD")) {
				print STDERR "Error: ". $f->filename()." (".join(",", @{$f->argument()}).") could not be written.\nNo yield info for that year in EXTRNAL_CG_YIELDS.\n";
				exit(1);
			}
			print STDERR "Info: ". $f->filename()." (".join(",", @{$f->argument()}).") omitted. No yield info for that year.\n";
			$self->delete_file($f);
			unlink $f->full_filename(0);##delete any old files to avoid mistakes
			unlink $f->full_filename(1);##delete any old files to avoid mistakes
		}
	}
}

