package MpmasCropExtLinkXN;

use strict;
use warnings;
use Exporter;
use Storable qw(dclone);
use Data::Dumper;
use List::Util qw[min max];
use CtUtilities qw(queryhash extqueryhash);
use MpmasInputfile;
use MpmasInputBlock;
our @ISA = qw(MpmasInputfile);

sub filename {
	return "ExpertnMpmasLinkTable";
}
sub leftmargin {
	return "";
}
sub required {
	my $self = shift;
	return ($self->config_entry("CROP_MODEL") == 3 and $self->config_entry("BIOVERSION") == 4 and  $self->config_entry("EXTERNAL_CROP_MODEL") eq "EXPERT-N");
}
sub prepare_shared{

}
sub prepare_special {
		my $self = shift;

		my $xnact = MpmasInputBlock->new(0,10);
		$xnact->add_row("LandUseID", "ManagementID", "SoilID", "WeatherID");
		
		if ($self->config_entry("STATICNRU") == 1 and $self->config_entry("EXTERNALCGFORMAT0")) {

			for my $o (@ {$self->get_global("Sorted_Xn_Activity_Objects")}) {#
			  for my $x ( "XNManagementID", "XNSoilID", "XNWeatherID") {
				 print STDERR "Error: No field external_crop_growth>$x defined for activity ".$o->id. "\n" and exit(1) unless (defined $o->subelement_field("external_crop_growth", "$x"));
			   }
			  $xnact->add_row(  $o->subelement_field("external_crop_growth", "link"), $o->subelement_field("external_crop_growth", "XNManagementID"), $o->subelement_field("external_crop_growth", "XNSoilID"), $o->subelement_field("external_crop_growth", "XNWeatherID") );
			  
			}
			
		}
		else {
			print STDERR "\nError: Missing EXTERNAL_CG_LINK [MPMAS TABLES].\nThis is required because EXTERNALCGFORMAT0 has been set to 0 or STATICNRU has been set to 0 or >=2\n
			and CROP_MODEL = 3 and BIOVERSION= 4\n and EXTERNAL_CROP_MODEL = EXPERT-N\n"  and exit(1) unless (defined $self->config_entry("EXTERNAL_CG_LINK"));
			my $xnlinktab = $self->config_entry("EXTERNAL_CG_LINK")->transform($self->get_dbh(),1);
			for my $o (@ {$self->get_global("Sorted_Xn_Activities")}) {#
				$xnact->add_row(	$o->[3], $xnlinktab->query([$o->[3]],2), $xnlinktab->query([$o->[3]],3), $xnlinktab->query([$o->[3]],4) );
			}
		}
		$xnact->add_empty_rows(3);		
		$self->add_block($xnact);
		
}
1;
