package MpmasCalibrationLanduseEdicMatlab;

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

sub filename {
	return "CalibrationLanduseEdicMatlab";
}
sub extension {
	return ".txt";
}
sub leftmargin {
	return "";
}
sub required {
	return defined $self->config_entry("EDICCALIBLU");
}

sub prepare_special {
	my $self = shift;
	my $dbh = $self->get_dbh;
	my $ediccaliblu = $self->config_entry("EDICCALIBLU")->transform($dbh, 2) ;

	my $ainfo = MpmasInputBlock->new(0,100);
	 $ainfo->add_row("ActivityID","LpCode","ActivityName","Lu","CropID","CropName","SoilType","Sum"
);
	 $ainfo->add_row();

	my $cropwatactid = 0;
	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)) { 
			die "Cropwat entry $f missing for activity $act!\n" unless (defined $cwa->subelement_field("cropwat", $f));
		}
		##
		
		  my $sale = $self->activity($cwa->subelement_field("cropwat", "sales_activity"));

		  die "Could not find the sales activity '".$cwa->subelement_field("cropwat", "sales_activity")."' for cropwat activity $act\n(check the #cropwat>sales_activity field)\n" unless (defined $sale);
		  my $yldrow = $self->constraint($cwa->subelement_field("cropwat", "yield_constraint"));
  		  die "Could not find the yield row '".$cwa->subelement_field("cropwat", "yield_constraint")."' for cropwat activity $act\n(check the #cropwat>yield_constraint field)\n" unless (defined $yldrow);
		  my $imid =  $irrigmethods->query([$cwa->subelement_field("cropwat", "irrigation_method")],9) || -1;
		  my $ipg = $cwa->subelement_field("cropwat", "ipg") || -1;
		  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, $cropwatactid++, $cwa->lp_column, $cwa->name, $cwa->subelement_field("edicmatlab","crop_id"), $cwa->subelement_field("edicmatlab","crop_name"), $cwa->subelement_field("cropwat", "soil"), $ipg, $imid, $cwa->subelement_field("cropwat", "yield_potential"), $cwa->subelement_field("cropwat", "yield_start"), $irrigmethods->query([$imid],6));

		  for my $m (@sortedmonths) {
			  my $d = $cwa->subelement_field("cropwat",  "waterdemand_$m") ||0;
			  push @row, $d;
		  }


		  $ainfo->add_row(@row);

	      }
	}
	$self->add_block($ainfo);

}
1;
