<?php

/**
 * CsMap2Proj.php
 *
 * A helper script to generate a Mentor Code -> Proj4 string lookup table using the common property that ties both of
 * them together: The EPSG code.
 *
 * For each CS-Map coordinate system with an epsg code, we fire off a request to spatialreference.org for the matching proj4 string
 *
 * Run this script sparingly as it will hammer spatialreference.org for proj4 strings for every CS-Map coordinate system with a proj4 string
 *
 * This script should be run from the command-line via the PHP CLI interpreter as opposed to from a web-browser. Invocation is like so:
 *
 *  php.exe CsMap2Proj.php
 */

//Guard against non-CLI execution
if (php_sapi_name() != "cli") {
	echo "This script can only be run via the PHP CLI interpreter<br />Usage: php.exe CsMap2Proj.php";
	exit;
}

include ('Common.php');
if(InitializationErrorOccurred())
{
    DisplayInitializationErrorText();
    exit;
}
include ('Utilities.php');

function get_proj4_string($epsgCode) {
	$ch = curl_init();
	$timeout = 5;
	$url = "http://www.spatialreference.org/ref/epsg/$epsgCode/proj4/";
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
	$data = curl_exec($ch);
	curl_close($ch);
	if (strpos($data, "Not found") !== false)
		return null;
	else
		return $data;
}

$file = fopen("csmap2proj4.js", "w");
fwrite($file, "/*\n csmap2proj4.js - A Mentor code to proj4 string lookup table\n\n This file was generated by CsMap2Proj.php\n */\n");

$grandTotal = 0;
$mappedTotal = 0;
$csFactory = new MgCoordinateSystemFactory();
$csCategories = $csFactory->EnumerateCategories();
for ($k = 0; $k < $csCategories->GetCount(); $k++) {
	$category = $csCategories->GetItem($k);
	echo ">>> Fetching CS-Map coordinate systems: $category <<<\n";
	$csCodes = $csFactory->EnumerateCoordinateSystems($category);
	$mapped = 0;
	$grandTotal += $csCodes->GetCount();
	for ($i = 0; $i < $csCodes->GetCount(); $i++) { 
		$csProps = $csCodes->GetItem($i);
		for ($j = 0; $j < $csProps->GetCount(); $j++) { 
			$prop = $csProps->GetItem($j);
			if (strcmp(strtolower($prop->GetName()), "code") == 0) {
				try 
				{
					$csCode = $prop->GetValue();
					$csWkt = $csFactory->ConvertCoordinateSystemCodeToWkt($csCode);
					if (strlen(trim($csWkt)) == 0) {
						echo "Skipping $csCode: Empty WKT\n";
						continue;
					}

					$epsg = $csFactory->ConvertWktToEpsgCode($csWkt);
					if ($epsg <= 0) {
						echo "Skipping $csCode: Invalid EPSG code - $epsg\n";
						continue;
					}

					if ($epsg == 3785 || $epsg == 4269 || $epsg == 4326 || $epsg == 102113 || $epsg == 900913) {
						echo "Skipping $csCode: EPSG code already defined by Proj4js - $epsg\n";
						continue;
					}

					try
					{
						$proj4 = get_proj4_string($epsg);
						if ($proj4 != null) {
							$line = "Proj4js.defs[\"EPSG:$epsg\"] = \"$proj4\"; //Mentor: $csCode\n";
							fwrite($file, $line);
							echo "Got proj4 string for: $csCode (EPSG:$epsg)\n";
							$mapped++;
						} else {
							echo "No proj4 string for: $csCode (EPSG:$epsg)\n";
						}
					}
					catch (Exception $ex)
					{
						echo "ERROR fetching EPSG $epsg: ".$ex->getMessage().". Skipping\n";
					}
				}
				catch (MgException $ex)
				{
					echo "MgException - ".$ex->GetExceptionMessage().". Skipping\n";
				}
			}
		}
	}
	$mappedTotal += $mapped;
	echo ">>> Mapped $mapped of ".$csCodes->GetCount()." to proj4 ($mappedTotal / $grandTotal processed) <<<\n";
}

fclose($file);
echo "=========== $mappedTotal of $grandTotal CS-MAP coordinate systems mapped to proj4js =================";

?>