package MpmasCropWat;

use strict;
use warnings;
use Exporter;
use Storable qw(dclone);
use Data::Dumper;
use MpmasInputfile;
use MpmasInputBlock;
use List::Util qw(max);
our @ISA = qw(MpmasInputfile);

sub filename {
	return "CropWat";
}
sub required {
      my $self = shift;
      return 1 if ($self->config_entry("CROP_MODEL") == 2);
}
sub prepare_shared {
      my ($self) = @_;
      my @cropwat_activities;
      for my $act ($self->sorted_activities) {
	    my $cwa = $self->activity($act);
	    if ($cwa->subelement_fields("cropwat")) {
	      #check if all required fields are defined
	      for my $f (qw(sales_activity yield_constraint irrigation_method ipg soil seasonality k_y yield_potential yield_start)) {
		      print STDERR "CropWat entry $f missing for activity $act!\n" and exit(1) unless (defined $cwa->subelement_field("cropwat", $f));
	      }
	      push @cropwat_activities, $cwa; 
	    }
      }
      $self->set_global("Sorted_CropWat_Activities", \@cropwat_activities );
}


sub prepare_special {
	my $self = shift;	
	my @sortedmonths = @{$self->config_entry("SORTEDIRRIGMONTHS")};
	my $watactcount = 0;
	my %ipghash;
	my %zerolabhash;

	my $irrigmethods = $self->config_entry("EDICIRRIGMETHODS_TAB");
	
	my $actblock = MpmasInputBlock->new(2,30);						
	$actblock->add_comment_row("ActivityID", "ActivityName", "Lpcolumn","Selling activity index",	"YieldIndex","SoilType","IPG","CropIrrigationType","IrrigationMethodID","Seasonality","KY","Potential yield","Start Value for Agent Yield Expectation", @sortedmonths);

	for my $cwa ( @{ $self->get_global("Sorted_CropWat_Activities")} ) {
		  my $act = $cwa->id;
		  $watactcount++;
		  my $sale = $self->activity($cwa->subelement_field("cropwat", "sales_activity"));
		  print STDERR "Could not find the sales activity '".$cwa->subelement_field("cropwat", "sales_activity")."' for cropwat activity $act\n(check the #cropwat>sales_activity field)\n"  and exit(1) unless (defined $sale);
		  my $yldrow = $self->constraint($cwa->subelement_field("cropwat", "yield_constraint"));
  		  print STDERR "Could not find the yield row '".$cwa->subelement_field("cropwat", "yield_constraint")."' for cropwat activity $act\n(check the #cropwat>yield_constraint field)\n" and exit(1) unless (defined $yldrow);
		  my $imid;
		  if (defined $irrigmethods) {
		      $imid	=	$irrigmethods->query([$cwa->subelement_field("cropwat", "irrigation_method")],9);
		  }
		  $imid = -1 if not (defined $imid);
		  my $ipg = $cwa->subelement_field("cropwat", "ipg");
		  $ipg = -1 if not (defined $ipg);
		  my $itype = 1;#Crop Irrigation Type 1,2 irrigated
		  $itype = 5 if ($imid == -1); #5,6 rainfed
		  $itype += 1 if ($cwa->type eq "MASperennial" or $cwa->type eq "MASswitch");#2,6 perennials
		  my @row = ($act, $cwa->name, $cwa->lp_column, $sale->lp_column, $yldrow->lp_row, $cwa->subelement_field("cropwat", "soil"), $ipg, $itype, $imid,$cwa->subelement_field("cropwat", "seasonality"), $cwa->subelement_field("cropwat", "k_y"), $cwa->subelement_field("cropwat", "yield_potential"), $cwa->subelement_field("cropwat", "yield_start"));
		  if ($self->backwards_compatibility(102) ) {
			for my $m (@sortedmonths) {
			    my $d = $cwa->subelement_field("cropwat",  "waterdemand_$m") ||0;
			    push @row, $d;
			}
		  }
		  else {
		      for my $m (@sortedmonths) {
			  my $d = $cwa->subelement_field("cropwat",  "kc_$m") || 0;
			  push @row, $d;
		      }
		  }
		  $ipghash{$ipg} += 1;
		  $actblock->add_row(@row);
		  #Register zero-labour activities for use below
		  if ($cwa->subelement_field("cropwat","zerolab") == 1)  {
			my $s = $cwa->subelement_field("cropwat","soil");
			$zerolabhash{$s} = $cwa->lp_column;
		
		  }
	}
	$actblock->add_empty_rows(3);
	$self->add_block($actblock);
	my $numipg = max(keys %ipghash) + 1;

	my $header = MpmasInputBlock->new(3,10);						
	$header->add_row("THE FAO CROPWAT MODEL");
	$header->add_row("1","INFORMATION ON CROP-WATER ACTIVITIES IN THE MATRIX");		
	$header->add_row("","1.1","Number of water crop activities", $watactcount);
	$header->add_row("","1.2","Number irrigation priority groups", $numipg);								
	$header->add_row("","1.3","Number of months with possible water stress",$self->config_entry("IRRIGMONTH"));								
	$self->add_block($header);										

	my $effrainparam = MpmasInputBlock->new(2,20);
	$effrainparam->add_row("2","PARAMETER VALUES TO CALCULATE EFFECTIVE RAINFALL");

	if ( $self->config_entry("EFFRAIN_TYPE") eq "USDA" or $self->config_entry("EFFRAIN_TYPE") eq "1" ) {
		$effrainparam->add_row("","Type of Equation", 1),
	}
	elsif ( $self->config_entry("EFFRAIN_TYPE") eq "Regression" or $self->config_entry("EFFRAIN_TYPE") eq "0") {
		$effrainparam->add_row("","Type of Equation", 0),
		$effrainparam->add_row("","Constant", $self->config_entry("EFFRAIN_CONST")),
		$effrainparam->add_row("","CWR",$self->config_entry("EFFRAIN_CWR"));
		$effrainparam->add_row("","CWR2",$self->config_entry("EFFRAIN_CWR2"));
		$effrainparam->add_row("","PREC",$self->config_entry("EFFRAIN_PREC"));
		$effrainparam->add_row("","PREC2",$self->config_entry("EFFRAIN_PREC2"));
		$effrainparam->add_row("","CWRPREC",$self->config_entry("EFFRAIN_CWRPREC"));	
	}
	else {
		print STDERR "Invalid type of equation for effective rainfall (". $self->config_entry("EFFRAIN_TYPE"). "). Can be either 'USDA' or 'Regression'." and exit(1);
	}

	$effrainparam->add_empty_rows(3);
	$self->add_block($effrainparam);
	my $zerolab = MpmasInputBlock->new(1,40);
	$zerolab->add_comment_row("2.2","Information for spatially-explicit land use (Flag -A22)");
	$zerolab->add_comment_row("Soil type", "LP activity index of zero-labor crop activity");
	for my $s (0..$self->config_entry("NSOIL") -1) {
		print STDERR "Error in CropWat: You did not define a zero-labour activity for soil-type $s!\n" and exit(1) unless (defined $zerolabhash{$s});
		$zerolab->add_row($s, $zerolabhash{$s});
	}
	$self->add_block($zerolab);
};
1;
