<?
/*Copyright (c) 2009, Dan "Ducky" Little & GeoMOOSE.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

/*
 * GeoMOOSE 2 Select Service 
 */

include('config.php');

# Turn off the warning reporting
error_reporting(E_ERROR | E_PARSE);

$projection = $CONFIGURATION['projection'];
$tempDirectory = $CONFIGURATION['temp'];

# A buffer for the 'select' shapes
$shape_buffer = $_REQUEST['shape_buffer'];
$selection_buffer = $_REQUEST['selection_buffer'];
if(!isset($shape_buffer)) { $shape_buffer = 0; }
if(!isset($selection_buffer)) { $selection_buffer = 0; }

# Get the Query Shape
$shape = $_REQUEST['shape'];
$selectShape = ms_shapeObjFromWkt($shape);

# This is the layer where shapes are selected from
$selectLayer = $_REQUEST['select_layer'];

# This is the layer from where feature information is queried
$queryLayer = $_REQUEST['query_layer']; 

$queryShapes = array();

# Load the mapbook
$mapbook = getMapbook();

# Select Layer and Query Layer are the Same, 
# just buffer the initial selection
$selectMap = getMapfile($mapbook, $selectLayer);
if(!isset($queryLayer) || $queryLayer == null || $selectLayer == $queryLayer) {
	array_push($queryShapes, $selectShape->buffer($shape_buffer));
} else {
	$queryMap = getMapfile($mapbook, $queryLayer);
	$layer = array_reverse(explode('/', $queryLayer));
	$layer = $layer[0];
	
	$shapeLayersToQuery = array();

	# Open the layers.
	$map = ms_newMapObj($CONFIGURATION['root'].$queryMap);
	if($layer == 'all') {
		for($i = 0; $i < $map->numlayers; $i++) {
			array_push($shapeLayersToQuery, $map->getLayer($i));
		}
	} else {
		array_push($shapeLayersToQuery, $map->getLayerByName($layer));
	}

	if($selectShape->type != MS_SHAPE_POLYGON) {
		# Small buffer converts points and lines to polygons
		$selectShape = $selectShape->buffer(.01);
	}
	for($i = 0; $i < sizeof($shapeLayersToQuery); $i++) {
		$shapeLayersToQuery[$i]->set('template','dummy.html');
		$shapeLayersToQuery[$i]->queryByShape($selectShape);
		$shapeLayersToQuery[$i]->open();
		for($r = 0; $r < $shapeLayersToQuery[$i]->getNumResults(); $r++) {
			$result = $shapeLayersToQuery[$i]->getResult($r);
			array_push($queryShapes, $shapeLayersToQuery[$i]->getFeature($result->shapeIndex, $result->tileIndex));
		}
		$shapeLayersToQuery[$i]->close();
	}
}

$map = ms_newMapObj($CONFIGURATION['root'].$selectMap);
$layersToQuery = array();
$shapesFound = array();

$layer = array_reverse(explode('/', $selectLayer));
$layer = $layer[0];
if($layer == 'all') {
	for($i = 0; $i < $map->numlayers; $i++) {
		array_push($layersToQuery, $map->getLayer($i));
	}
} else {
	array_push($layersToQuery, $map->getLayerByName($layer));
}

# Build a massive shape
$queryShape = array_pop($queryShapes);
$queryShape = $queryShape->buffer($selection_buffer);
foreach($queryShapes as $shape) {
	if($shape->type != MS_SHAPE_POLYGON and $selection_buffer == 0) {
		$shape = $shape->buffer(.0001);
	}
	$queryShape = $queryShape->union_geos($shape->buffer($selection_buffer));
}


$foundShapes = array();
$attributes = false;
$results = '';

for($i = 0; $i < $map->numlayers; $i++) {
	$layer = $map->getLayer($i);
	$layer->set('status', MS_OFF);	# Turn off extraneous layers
}

foreach($layersToQuery as $layer) {
	$layer->set('template', $layer->getMetadata('select_record'));
	if($layer->getMetadata('select_header')) {
		$layer->set('header', $layer->getMetadata('select_header'));
	}
	if($layer->getMetadata('select_footer')) {
		$layer->set('footer', $layer->getMetadata('select_footer'));
	}
	$layer->set('status', MS_DEFAULT);
	$map->queryByShape($queryShape);
	$results = $results . $map->processquerytemplate(array(), false);
	$layer->open();
	$attributes = $layer->getItems();
	for($r = 0; $r < $layer->getNumResults(); $r++) {
		$result = $layer->getResult($r);
		array_push($foundShapes, $layer->getFeature($result->shapeindex, $result->tileindex));
		#$sh = $lay->getFeature($res->shapeindex, $res->tileindex);
	}
	$layer->close();
}




$fields = array();
foreach($attributes as $attribute) {
	# this is a hack in need of much fixing, but it actually kinda works because
	# "C" fields work like varchars, not fixed width character fields.
	array_push($fields, array($attribute, "C", 128));
}

$uniqueId = 'select_'.getmypid().time();
$dbaseFilename = $tempDirectory.$uniqueId.'.dbf';
$shapeFilename = $tempDirectory.$uniqueId;

# Create a Dbase File
dbase_create($dbaseFilename, $fields);
$dbase = dbase_open($dbaseFilename, 2);

# Set up a few variables for substitution later
$dict = array();
$dict['LAYER_TYPE'] = 'POLYGON';
$dict['UNIQUEID'] = $uniqueId;
$dict['QUERYID'] = $uniqueId;
$dict['SHAPEPATH'] = $tempDirectory;

# Create the shapefile
$shapeFileType = MS_SHP_POLYGON;
if($foundShapes[0]->type == MS_SHAPE_POINT) {
	$shapeFileType = MS_SHP_POINT;
	$dict['LAYER_TYPE'] = 'POINT';
}

$shapefile = ms_newShapefileObj($shapeFilename, $shapeFileType);
foreach($foundShapes as $shape) {
	$recordArray = array();
	foreach($attributes as $attribute) {
		array_push($recordArray, $shape->values[$attribute]);
	}
	dbase_add_record($dbase, $recordArray);
	$shapefile->addShape($shape);
}
$shapefile->free();
dbase_close($dbase);

# Process and output the template.
# $results = $map->processquerytemplate(array(), false);

# Form the mapfile.
$mapfile = implode('', file($CONFIGURATION['highlight_map']));
$mapfile = processTemplate($mapfile, $dict);

$mapfileOut = fopen($tempDirectory.'/'.$uniqueId.'.map', 'w+');
fwrite($mapfileOut, $mapfile);
fclose($mapfileOut);


# All that work for a dozen lines of output.
header('Content-type: application/xml');
print "<results>";
print "<script><![CDATA[";

# This could be extended to better represent the selection and query polygon shapes later.
# Right now, it sets the layer to use the mapserver_url and then points mapserver to the 
# proper map.
print " GeoMOOSE.changeLayerUrl('highlight', CONFIGURATION.mapserver_url);";
print " GeoMOOSE.updateLayerParameters('highlight', { 'map' : '".$tempDirectory."/".$uniqueId.".map'});";
print " GeoMOOSE.turnLayerOn('highlight/all');";
print " GeoMOOSE.refreshLayers('highlight/all');";
print "]]></script>";
print "<html><![CDATA[";
print '<b>Found Shapes: </b>'.sizeof($foundShapes).'<br/>';
print "<b>Query ID: </b>" . $uniqueId.'<br/>';
print processTemplate($results, $dict);
print "]]></html></results>";

function processTemplate($str, $dict) {
	foreach($dict as $k => $v) {
		$str = str_replace('['.$k.']', $v, $str);
	}
	return $str;
}
?>
