package MpmasCropDbgActivityID;

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 "CropActivityId";
}

sub required {
	my $self = shift;
	return ($self->config_entry("CROP_MODEL") == 3);
}
sub prepare_shared{
	my $self = shift;
	my $dbh = $self->get_dbh;
	#Make a selling activity and yield balance row registry for XN-products

	#print STDERR "Error: You activated the external crop growth model (CROP_MODEL = 3), but did not set LANDSCAPE_MODEL = 3\n" and exit(1) unless ($self->config_entry("LANDSCAPE_MODEL") == 3);

#	my %xnsellingindex;
#	my %xnproductrowindex;
#	for my $i ($self->sorted_activities) {
#		my $k = $self->activity($i);
#		last unless (lc($k->type) eq "massell" or lc($k->type) eq "masbuy");
#		my $z = $k->subelement_field("external_crop_growth", "product");
#		$xnsellingindex{$z} =  $k->lp_column if (defined $z and not $z eq "-1");
#
#	}
#	for my $k ($self->constraints) {
		#my $z = $k->subelement_field("external_crop_growth", "product");
		#$xnproductrowindex{$z} =  $k->lp_row if (defined $z and not $z eq "-1");
	#}
	my $NumCropActTotal = 0;
	my @soilcount;
	my %xnactivity_lookup;
	my @xnactivities;
	my @persoilxnactivities;
	for my $k ($self->sorted_activities) {
		my $i = $self->activity($k);
		my $curlink = $i->subelement_field("external_crop_growth", "link");
		
		if (defined $curlink and $curlink > -1) {
			$NumCropActTotal++ ;
			my $soil = $i->subelement_field("external_crop_growth", "soil");
						$soilcount[$soil] += 1;

			my @newxnact;
			$xnactivity_lookup{$curlink} = $i;
			$newxnact[2] = $i->attr("name");
			$newxnact[3] = $curlink;
			$newxnact[4] = $soil;
			$newxnact[5] = $i->subelement_field("external_crop_growth", "crop_type");
			$newxnact[6] = $i->subelement_field("external_crop_growth", "priority");

			my $pb = $i->subelement_field("external_crop_growth", "product1_sales_activity");
			if (defined $pb and not $pb eq "-1"  and not $pb eq "0") {
				my $ao = $self->activity($pb);
				print STDERR "Error in external crop growth interface: Activity ". $i->id." is associated to sales activity $pb, but no activity $pb has been defined\n" and exit(1) unless (defined $ao);
				$newxnact[7] = $ao->lp_column;
			}
			else {
			    $newxnact[7] =  -1;
			}
			$newxnact[8] = $i->subelement_field("external_crop_growth", "initial_yield_product1");
			$newxnact[9] = $i->subelement_field("external_crop_growth", "initial_yield_product2");
			$newxnact[10] = $i->lp_column;
			push @xnactivities, [ @newxnact  ];

			my @persoil;
			$persoil[1] = $curlink;
			$persoil[2] =$soil;
			$persoil[3] = $i->lp_column;

			$pb = $i->subelement_field("external_crop_growth", "product1_balance");
			if (defined $pb and not $pb eq "-1"  and not $pb eq "0") {
				my $co = $self->constraint($pb);
				print STDERR "Error in external crop growth interface: Activity ". $i->id." is associated to product balance $pb, but no constraint $pb has been defined\n" and exit(1) unless (defined $co);
				$persoil[4] = $co->lp_row;
			}
			else {
			    $persoil[4] =   -1;
			}
			$pb = $i->subelement_field("external_crop_growth", "product2_balance");
			if (defined $pb and not $pb eq "-1"  and not $pb eq "0") {
				my $co = $self->constraint($pb);
				print STDERR "Error in external crop growth interface: Activity ". $i->id." is associated to product balance $pb, but no constraint $pb has been defined\n" and exit(1) unless (defined $co);
				$persoil[5]  = $co->lp_row;
			}
			else {
			    $persoil[5] =   -1;
			}

			push @persoilxnactivities, [ @persoil];
		}
	}
	my @sortedxnactivities = sort { $a->[4]  <=> $b->[4] ||   $a->[10] <=> $b->[10]  } @xnactivities;
	my @sortedxnactivitiespersoil = sort {   $a->[2]  <=> $b->[2] ||   $a->[3] <=> $b->[3]  } @persoilxnactivities;

	print STDERR  "Error for external crop growth model: not the same number of activities for all soil types!!!\n" and exit(1) unless ( min (@soilcount) == max (@soilcount) );
	$self->{NumCropActPerSoil} = min (@soilcount);
	$self->{NumCropActTotal} = $NumCropActTotal;
	#register shared variables
	$self->set_global("Sorted_Xn_Activities",\@sortedxnactivities);
	$self->set_global("Sorted_Xn_Activities_Per_Soil",\@sortedxnactivitiespersoil);
	$self->set_global("Xn_Activity_Lookup",\%xnactivity_lookup);
	my @sorted_xn_activity_objects = map {$xnactivity_lookup{$_->[3]} } @sortedxnactivities;
	$self->set_global("Sorted_Xn_Activity_Objects", \@sorted_xn_activity_objects);
}
sub prepare_special {
		my $self = shift;

		my $sortedxnactivities = $self->get_global("Sorted_Xn_Activities");
		my $sortedxnactivitiespersoil = $self->get_global("Sorted_Xn_Activities_Per_Soil");

		my $xntop = MpmasInputBlock->new(2,10);
		$xntop->add_comment_row("External CROP COEFFICIENTS");
		$xntop->add_comment_row("This links the external crop growth model to the LP tableau");
		$xntop->add_empty_rows(3);

		$xntop->add_row("1","CROP ACTIVITIES");	
		$xntop->add_row("1.1","INFO ABOUT THE CROP ACTIVITIES");
		$xntop->add_row("", "Number of crop activities per soil type", $self->{NumCropActPerSoil});
		$xntop->add_row("", "Number of crop activities (total over all soil types)", $self->{NumCropActTotal});		
		$xntop->add_row("", "Number of cropping seasons per year",	$self->config_entry("XNSEASONS") );	
		$xntop->add_empty_rows(3);
		$self->add_block($xntop);

		my $xnact = MpmasInputBlock->new(3,30);
		$xnact->add_comment_row("","","Crop activities (sorted by soil type)", " Link ID", "Soil  type", "Crop type", "Priority", "Output ID", "Initial crop yield", "Initial stover yield");
		$xnact->add_table($sortedxnactivities);
		$xnact->add_empty_rows(3);
		$self->add_block($xnact);

		my $xnpersoil = MpmasInputBlock->new(3,40);
		$xnpersoil->add_row("2","NUTRIENT RESPONSE UNITS");
		$xnpersoil->add_row("2.1","LP COLUMN AND ROW INDICES");
		$xnpersoil->add_row("","Note: number of rows per NRU must equal maximum number of activites per soil type");	
		$xnpersoil->add_comment_row("","Link ID","Soil Type",	"LP index of activity",	"LP index of crop yield constraint","LP index of stover yield constraint"); 			
		$xnpersoil->add_table($sortedxnactivitiespersoil);
		$xnpersoil->add_empty_rows(3);
		$self->add_block($xnpersoil);
		
}
1;
