package MpmasCropWatPrecipitation;

use strict;
use warnings;
use Exporter;
use Storable qw(dclone);
use Carp ;
use Data::Dumper;
use CtUtilities qw(queryhash extqueryhash get_unique);
use MpmasInputfile;
use MpmasInputBlock;
use IndexedTable;
our @ISA = qw(MpmasInputfile);

sub filename {
	my $self = shift;
	return "ActualPrecipitation0";
}

sub required {
	my $self = shift;
	return ($self->config_entry("CROP_MODEL") == 2 );
}
sub prepare_shared {

}

sub prepare_special {
	my $self = shift;	
	my $regionhash = $self->config_entry("regionhash");
	my @sortedsectors = @{$self->config_entry("SORTEDSECTORS")};
	my @sortedmonths = @{$self->config_entry("SORTEDIRRIGMONTHS")};
	
	my $dbh = $self->get_dbh;
	my $precipacttab = $self->config_entry("CROPWAT_PRECIPACTUAL")->transform($dbh, 3);
	my $precipexptab = $self->config_entry("CROPWAT_PRECIPEXPECT")->transform($dbh, 2);

	my $head = MpmasInputBlock->new(2, 10);

	$head->add_row("THE CROPWAT PRECIPITATION (TIME SERIES) FILE");
	$head->add_row("1","PRECIPITATION");
	$head->add_empty_rows(1);

	$head->add_row("","Type of Input 0: yearly input", 0 );
	$head->add_row("","Flag: is data given for each sector (0 no, 1: yes)", 1 );
	$head->add_row("","Number of years",  $self->config_entry("ENDYEAR") -$self->config_entry("STARTYEAR")  + 1);
	$head->add_comment_row("","Note: Year 0 is the initial expectation, and should be given at the end. (Does not count for number of years.)");
	$head->add_empty_rows(2);
	$head->add_comment_row("","","","","Months");
	$head->add_comment_row("GisID", "Sector Name", "Sector MpmasId", "Year", @sortedmonths);
	for my $sec (0..$#sortedsectors) {
	      my $secid = $sortedsectors[$sec];
	      #Actual Precipitation time series
	      for my $y ($self->config_entry("STARTYEAR")..$self->config_entry("ENDYEAR")) {
		      my @row;
		      for my $m (@sortedmonths) {
			      push @row, sprintf("%.2f",$precipacttab->query([$secid, $y, $m],4));
		      }
		      $head->add_row($secid,$regionhash->{$secid}->{code}, $sec,$y, @row);
	      }
	      #Expected precipitation
	      my @row;
	      for my $m (@sortedmonths) {
		      push @row, sprintf("%.2f",$precipexptab->query([$secid, $m],3));
	      }
	      $head->add_row($secid,$regionhash->{$secid}->{code}, $sec,0, @row);
	  
	      $head->add_empty_rows(2);
	}
	$self->add_block($head);
}
1;