package MpmasMapDummies;

use strict;
use warnings;
use Exporter;
use Storable qw(dclone);
use Data::Dumper;
use CtUtilities qw(queryhash extqueryhash);
use MpmasInputfile;
use MpmasInputBlock;
use EnhancedGrid;
use File::Path;

our @ISA = qw(MpmasInputfile);

sub filename {
	my $self = shift;
	my $temp = $self->file_suffix;
	return "MapSet";
}

sub required {
	my $self = shift;
	return 1 if ($self->config_entry("GENERATE_MAPS") > 0);
	return 0;
}

sub agents {
    $_[0]->{agentlist};
}

sub prepare_shared {
	my ($self, $sexagedef, $householdhash, $assethash, $agentsinclu) = @_;

	unless( $self->config_entry("ASSETDISTTYPE") == 2) {
		print STDERR "Error: GENERATE_MAPS > 0 not possible for ASSETDISTTYPE < 2\n";
		exit(1);
	}





}
sub prepare_special {
	my ($self, $sexagedef, $householdhash, $fixcosthash, $assethash, $agentinfo, $parent) = @_;


	my $cellsize	=	sqrt($self->config_entry("CELLSIZE") ) * 100;

	

	my @soilarray;
	my @farmsteadarray;
	my @propertyarray;
	my @networkarray;
	my @clusterarray;
	my @poparray;
	my @sectorarray;

	
	for my $curAgent ($agentinfo->query([],0)) {
		my $nplots = 1;
		$nplots = $agentinfo->query_by_columnname([$curAgent], "NumberOfPlots") if ($agentinfo->exists_columnname("NumberOfPlots"));
#		my @slist;
#		for my $s (@attr_to_distribute) {
#			my $n_of_s = sprintf("%.0f",$curAgent->get_attribute($s->{field}));
#			push @soilarray, ($s->{soil_code}) x $n_of_s; 
#			$nplots += $n_of_s;
#		}
        my %soiltypeAreas;
        my $total = 0;
        for my $s ( 0..$self->config_entry("NSOIL") - 1) {       
            if ($agentinfo->exists_columnname("NumberOfPlots". $s)){
                my $area = $agentinfo->query_by_columnname([$curAgent], "NumberOfPlots".$s);
                $total += $area;
                if ($area > 0) {
                    $soiltypeAreas{$s} =  $area;
                }
            }
        }
        if(scalar(keys %soiltypeAreas)> 0 && $total != 0 && $total != $nplots) {
            print STDERR "Error in AGENT_INFO table: NumberOfPlots ($nplots) does not fit sum of plots for individual soil types ($total) [Agent: $curAgent]!\n";      
            exit(1);    
        }
		if ($nplots > 0) { 
			push @farmsteadarray, $curAgent, (-1) x ($nplots -1);
			
			push @propertyarray, ($curAgent) x $nplots;
			
			if ($total == 0 || scalar(keys %soiltypeAreas) == 0) {
    			push @soilarray, (0) x $nplots;
    		}
			else {
			    for my $s (keys %soiltypeAreas) {
    			    push @soilarray, ($s) x  $soiltypeAreas{$s};
    			}
			}

			push @sectorarray, (0) x ($nplots) ;

			my $n = 0;
			$n = $agentinfo->query_by_columnname([$curAgent], "NetworkID") if ($agentinfo->exists_columnname("NetworkID"));
			push @networkarray, $n, (-1) x ($nplots -1) ;

			my $c = 0;
			$c = $agentinfo->query_by_columnname([$curAgent], "ClusterID") if ($agentinfo->exists_columnname("ClusterID"));
			push @clusterarray, $c, (-1) x ($nplots -1) ;
			
			my $p = 0;
			$p = $agentinfo->query_by_columnname([$curAgent], "PopulationID") if ($agentinfo->exists_columnname("PopulationID"));
			push @poparray, $p, (-1) x ($nplots -1) ;
			

		};
		
	}
	my $mapheight = int(sqrt(scalar @soilarray));
	$self->{MAPS_READY}->{soilmap} 		= EnhancedGrid->create_map_from_sequence(\@soilarray, $mapheight,-1, "SOILMAP", $cellsize);
	$self->{MAPS_READY}->{farmsteadmap} 	= EnhancedGrid->create_map_from_sequence(\@farmsteadarray, $mapheight,-1, "FARMSTEADMAP", $cellsize);
	$self->{MAPS_READY}->{propertymap} 	= EnhancedGrid->create_map_from_sequence(\@propertyarray, $mapheight,-1, "PROPERTYMAP", $cellsize);
	$self->{MAPS_READY}->{clumap} 		= EnhancedGrid->create_map_from_sequence(\@clusterarray, $mapheight,-1, "CLUSTERMAP", $cellsize);
	$self->{MAPS_READY}->{popmap} 		= EnhancedGrid->create_map_from_sequence(\@poparray, $mapheight,-1, "POPULATIONMAP", $cellsize);
	$self->{MAPS_READY}->{netmap} 		= EnhancedGrid->create_map_from_sequence(\@networkarray, $mapheight,-1, "NETWORKMAP", $cellsize);
	$self->{MAPS_READY}->{secmap} 		= EnhancedGrid->create_map_from_sequence(\@sectorarray, $mapheight,-1, "SECTORMAP", $cellsize);


};

sub write {
	my ($self,$mode,$cur,$valuetab) = @_;
	return if ($mode == 1);
	#print "in Inputfile: $self,$mode,$cur, $valuehash\n";
	
	print "\e[K \r";	
	print "Writing maps...\r";
	
    
    my $mapdir = "gis/";
	$mapdir = $self->config_entry("MAPS") if (defined $self->config_entry("MAPS"));
	
	my $mapdir_first = $self->outdir;
	
	
	$mapdir_first =~ s/\/?dat\/*$//; #remove dat/ and any trailing /
	
    $mapdir = $mapdir_first."/". $mapdir;


	$mapdir = $mapdir ."/" unless ($mapdir =~/\/$/);
	$mapdir .= $self->mname()."/";
	
	&mkpath($mapdir);
	
	$self->{MAPS_READY}->{farmsteadmap}->save_as_ascii($mapdir."CatchMap00Farm.txt");
	$self->{MAPS_READY}->{propertymap}->save_as_ascii($mapdir."CatchMap00Prop.txt");
	if (defined $self->config_entry("TERRAINMAPSTUB")) {
		$self->{MAPS_READY}->{soilmap}->save_as_ascii($mapdir."CatchMap00".$self->config_entry("TERRAINMAPSTUB").".txt");
	}
	else {
		$self->{MAPS_READY}->{soilmap}->save_as_ascii($mapdir."CatchMap00Soil.txt");
	}
	$self->{MAPS_READY}->{clumap}->save_as_ascii($mapdir."CatchMap00Clu.txt");
	$self->{MAPS_READY}->{popmap}->save_as_ascii($mapdir."CatchMap00Pop.txt");
	$self->{MAPS_READY}->{netmap}->save_as_ascii($mapdir."CatchMap00Netw.txt");
	$self->{MAPS_READY}->{secmap}->save_as_ascii($mapdir."CatchMap00Sector.txt");	
	$self->{MAPS_READY}->{secmap}->save_as_ascii($mapdir."CatchMap00Catchment.txt");#same as sector for these simple dummy maps
	

};
1;


