package MpmasRegion;

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

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

sub required {
	return 1;
}
sub prepare_shared {
	my $self = shift;
	my $dbh = $self->get_dbh;
	#Number of Sectors in Region (for BasicData and Region)
	my $regionhash = {};	
	
	my $r1 = $self->config_entry("REGION");	
	
	if (not $r1 and $self->config_entry("LANDSCAPE_MODEL") > 0   ) {
		print STDERR "Error: You activated the LANDSCAPE_MODEL, but did not supply a REGION table\n" ;
		exit(1);
	}
	elsif (not $r1) {
		my %hash = (
		     0 => ["default_region",0,0,1,0]
		);
		$regionhash = IndexedTable->create_from_hash(\%hash, 1) ;
	}
	else {
	      #$regionhash = queryhash($dbh, "$r1", "gisid");
	      $regionhash = $r1->transform($dbh,1);
	}
	my @rgs = $regionhash->query([],0);
	$self->set_config_entry("VILLAGES", scalar @rgs);
	$self->set_config_entry("NSECTORS", scalar @rgs);
	my @tmp;
	my $j = 0;
	for my $r3 (@rgs){
		$tmp[$j] = $regionhash->query([$r3],3);
		$j += 1;
	}
	my @tmp2 = get_unique(@tmp);
	$self->set_config_entry("DISTRICTS", scalar @tmp2);
		

	#Sector Seeds
	my $seedhash;
	if (not defined $self->config_entry("SEEDS")) {
	  my %hash = map {$_ => 42} @rgs;
	  $seedhash = IndexedTable->create_from_hash(\%hash, 1) ;
	}
	else {
	  $seedhash = $self->config_entry("SEEDS")->transform($dbh, 1);
	}
	 
	

	
	if  (($self->config_entry("LANDSCAPE_MODEL") == 1 or $self->config_entry("LANDSCAPE_MODEL") == 2)  and $self->config_entry("IRRIGATION") ) {
		my $inflows = $self->config_entry("EDICINFLOWEXPECT")->transform($dbh,2) ;
		#Sort inflows
		my @sorted_inflows = sort {$a <=> $b} $inflows->query([],0);  
		$self->set_config_entry("SORTEDINFLOWS", \@sorted_inflows);
		$self->set_config_entry("INFLOWTAB", $inflows);
		if (scalar @sorted_inflows != $self->config_entry("NINFLOWS")) {
		    print "WARNING: Specified number of inflows does not match number of inflows in EDICINFLOWEXPECT\nThe later is being used.\n";
		    $self->set_config_entry("NINFLOWS", scalar @sorted_inflows);
		}
	}

	my @sorted_sectors = sort{$regionhash->query([$a], 6) <=> $regionhash->query([$b], 6)} $regionhash->query([],0);
	$self->set_config_entry("SORTEDSECTORS", \@sorted_sectors);
	$self->set_config_entry("regionhash", $regionhash);
	$self->set_config_entry("seedhash", $seedhash);
	
}

sub prepare_special {
	my $self = shift;	
	my $regionhash = $self->config_entry("regionhash");
	my $seedhash = $self->config_entry("seedhash");
	
	my $regionhead = MpmasInputBlock->new(2, 10);
	$regionhead->add_row("The REGION FILE");
	$regionhead->add_row("General information");
	$regionhead->add_row("Variable","Explanation");
	$regionhead->add_row("NumSectors","Corresponds to lines in table", $self->config_entry("NSECTORS"));
	
	if  ($self->backwards_compatibility(95) ) { 
		$regionhead->add_row("Hydrological Model","", $self->config_entry("LANDSCAPE_MODEL"));
		$regionhead->add_row("Channel Model","Currently not used ???", "-1") if ( $self->config_entry("LANDSCAPE_MODEL") > 0 ) ;
	}
	elsif ($self->backwards_compatibility(102)  )  {
		$regionhead->add_row("Irrigation (yes/no)","", $self->config_entry("IRRIGATION"));
	};
	if  ($self->backwards_compatibility(95) ) {
		$regionhead->add_row("numInflows","Corresponds to number of inflows", $self->config_entry("NINFLOWS")) if $self->config_entry("LANDSCAPE_MODEL") > 0;
		$regionhead->add_row("ValuesPerInflow", "",$self->config_entry("VINFLOWS")) if $self->config_entry("LANDSCAPE_MODEL") > 0;
	}
	else {
		$regionhead->add_row("numInflows","Corresponds to number of inflows", $self->config_entry("NINFLOWS")) if $self->config_entry("IRRIGATION") == 1;
		$regionhead->add_row("ValuesPerInflow", "",$self->config_entry("VINFLOWS")) if $self->config_entry("IRRIGATION") == 1;
	};
	$self->add_block($regionhead);
	
	my $region = MpmasInputBlock->new(1, 20);
	my (@maxcaphead, @secshhead);
	for my $i (0..$self->config_entry("NINFLOWS") -1) {
	    $maxcaphead[$i] = "Max Cap. Sector/ Inflow $i";
	    $secshhead[$i] = "Sector Share of Inflow $i";
	}
	$region->add_comment_row("SectorID","Sector name", "Used? (yes/no)", "Sub-sector (yes/no)", "Catchm. ID","GIS-ID","Sector Seed",  "Initial ReUse Coefficient",	"Canal Efficiency",	"Water System Efficiency due to overnight storage", "b", "g", @maxcaphead, @secshhead, "Num Lottery Params" );

	my @sortedsectors = @{$self->config_entry("SORTEDSECTORS")};
	my $rw = 0;
	
	my $secsh = 0;
	if ($self->config_entry("EDICSECTORRIGHTS")) {
		my $dbh = $self->get_dbh;
		$secsh = $self->config_entry("EDICSECTORRIGHTS")->transform($dbh,2);
	}
	for my $i (@sortedsectors) {
		my @regiontab;
		$regiontab[0] = $rw;
		my $cl = 1;
		my @cnames1= qw(code beingused subsector catchid   );
		for my $j (2,5,4,3){
			croak "Missing entry $cnames1[$j - 1] for Sector $i in MpmasRegion\n" unless (defined $regionhash->query([$i],$j));
			$regiontab[$cl++] = $regionhash->query([$i],$j); 
		}
		$regiontab[$cl++] = $i;#gisid
		$regiontab[$cl++] = $seedhash->query([$i],2);#seed
		if  ($self->backwards_compatibility(95) ) { $regiontab[$cl++] = 0}; #numparcels		

		if ($self->config_entry("IRRIGATION") == 1 or ($self->backwards_compatibility(95) and $self->config_entry("LANDSCAPE_MODEL") > 0) ) {

			my @cnames2 = qw(reuse canalefficiency watersystemefficiency bcoeff gcoeff );
			for my $j (7..11){
				croak "Missing entry $cnames2[$j -1 ] for Sector $i in MpmasRegion\n" unless (defined $regionhash->query([$i],$j));
				$regiontab[$cl++] = $regionhash->query([$i],$j); 			
			}
			if ($secsh) {
			    my $gisid = $i;
			    for my $inf (@{$self->config_entry("SORTEDINFLOWS")}) {
				$regiontab[$cl++]=  $secsh->query([$gisid,$inf],4) || 0;
			    }
			    for my $inf (@{$self->config_entry("SORTEDINFLOWS")}) {
				$regiontab[$cl++]= sprintf("%.4f",$secsh->query([$gisid,$inf],3) ||0  ) ;
			    }
			}
			else{
			    $regiontab[$cl++] = 0; 
			    $regiontab[$cl++] = 0;     
			}
			$regiontab[$cl++] = $regionhash->query([$i],12) || 0; 
			
		}
		$region->add_row(@regiontab);
		$rw += 1;
	}
	$self->add_block($region);
		
}
1;
