package MpmasActualWaterRights;

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

sub required {
	my $self = shift;
	return ($self->config_entry("LANDSCAPE_MODEL") == 1 and $self->config_entry("EDICAGENTRIGHTS"));
}
sub prepare_shared {

}

sub prepare_special {
	my $self = shift;	
	my $regionhash = $self->config_entry("regionhash");
	my @sortedsectors = @{$self->config_entry("SORTEDSECTORS")};
	my @sortedinflows = @{$self->config_entry("SORTEDINFLOWS")};
	my $dbh = $self->get_dbh;
	my $rightstab = $self->config_entry("EDICAGENTRIGHTS")->transform($dbh, 4);

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

	$head->add_row("THE ACTUAL WATER RIGHTS FILE");
	$head->add_row("1","Distribution of water rights over all agents (1 row = 1 water right)");
	$head->add_empty_rows(2);
	$head->add_comment_row("SectorGisID", "SectorName", "CatchID", "SectorID", "FarmsteadID", "Inflow", "Share" );
	for my $ctch (sort {$a <=> $b} $rightstab->query([],0)) {
	    for my $sec (0..$#sortedsectors) {
		my $gisid = $sortedsectors[$sec];
		for my $inf (0..$#sortedinflows) {
			my $infid = $sortedinflows[$inf];
			next unless (defined $rightstab->query([$ctch, $gisid],0) );
			for my $fst (sort {$a <=> $b} $rightstab->query([$ctch, $gisid],0)) {
			
			     	 $head->add_row($gisid,$regionhash->query([$gisid],2),$ctch, $sec, $fst, $inf, sprintf("%.4f",$rightstab->query([$ctch, $gisid, $fst, $infid],5))) if (defined $rightstab->query([$ctch, $gisid, $fst, $infid],5));

			}
		}
	    }
	}
	$self->add_block($head);
}
1;
