<?php
/*
 * Project: NodeMap2.0
 * File: KMLHandler.class.php
 * Purpose: Creating of editing KML files
 */

define('PLACEMARK_GREEN', 'http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png');
define('PLACEMARK_ORANGE', 'http://www.google.com/intl/en_us/mapfiles/ms/micons/orange-dot.png');
define('PLACEMARK_RED', 'http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png');

class KMLFile {
	private $template = '
		<\?xml version="1.0" encoding="UTF-8"?>
		<kml xmlns="http://www.opengis.net/kml/2.2">
			<Document>
				<name>Wireless Leiden Interactive Nodemap 2.0</name>
				<open>1</open>
				<description>Wireless Leiden Interactive Nodemap 2.0</description>
				<Style id="greenArrowIcon">
					<IconStyle>
						<Icon>
							<href>%PLACEMARK_GREEN%</href>
						</Icon>
					</IconStyle>
				</Style>
				<Style id="orangeArrowIcon">
					<IconStyle>
						<Icon>
							<href>%PLACEMARK_ORANGE%</href>
						</Icon>
					</IconStyle>
				</Style>
				<Style id="redArrowIcon">
					<IconStyle>
						<Icon>
							<href>%PLACEMARK_RED%</href>
						</Icon>
					</IconStyle>
				</Style>
				<Folder>
					<name>Nodes</name>
					<description>Nodes from the Wireless Leiden network</description>
					<LookAt>
						<longitude>52.161087</longitude>
						<latitude>4.490153</latitude>
						<altitude>0</altitude>
						<heading>0</heading>
						<tilt>0</tilt>
						<range>500</range>
					</LookAt>
					%CONTENT%
				</Folder>
			</Document>
		</kml>';

	static $fileFirst = 'type,host_name,has_been_checked,check_execution_time,current_state,last_hard_state,last_check,problem_has_been_acknowledged';
	private $fileContent = array('string', 'string', 'integer', 'double', 'integer', 'integer', 'integer', 'integer');

	private $KMLPlacemarks;

	/*
	 * Function: __construct (constructor)
	 * Parameters: -
	 * Function: Creating a new KMLFile
	 */
	public function __construct() {
		$this->KMLPlacemarks = array();
	}

	public function addPlacemark(KMLPlacemark $placemark) {
		$this->KMLPlacemarks[] = $placemark;
	}

	public function toString() {
		$toString = $this->template;

		$placemarkString = '';
		$placemarkCount = count($this->KMLPlacemarks);
		for ($i = 0; $i < $placemarkCount; $i++) {
			$placemarkString .= $this->KMLPlacemarks[$i]->toString();
		}

		$toString = str_replace('%PLACEMARK_GREEN%', PLACEMARK_GREEN, $toString);
		$toString = str_replace('%PLACEMARK_ORANGE%', PLACEMARK_ORANGE, $toString);
		$toString = str_replace('%PLACEMARK_RED%', PLACEMARK_RED, $toString);
		$toString = str_replace('%CONTENT%', $placemarkString, $toString);

		return $toString;
	}

	public function write($filename) {
		// TODO: Write KMLFile to a KML file
	}

	/*
	 * Function: getPlacemarkByName
	 * Parameters: string $name
	 * Function: Find the first KMLPlacemark with the name $name and return its position. If not found, return false
	 */
	public function getPlacemarkByName($name) {
		$nodesCount = count($this->KMLPlacemarks);
		for ($i = 0; $i < $nodesCount; $i++) {
			if ($this->KMLPlacemarks[$i]->getName() == $name) {
				return $i;
			}
		}
		return false;
	}

	/*
	 * Function: parseLocationFile
	 * Parameters: string $file
	 * Function: Parse the node location file updating or adding KMLPlacemark objects to the current KMLFile object
	 */
	public function parseLocationFile($file) {
		$nodesCount = preg_match_all('/\[[a-zA-Z0-9]*\]/i', $file, $nodes, PREG_OFFSET_CAPTURE);
		for ($i = 0; $i < $nodesCount; $i++) {
			// TODO: Needs checking for parsing errors
			$location	= $this->findInLocationFile($file, 'location', $nodes[0][$i][1]);
			$status		= $this->findInLocationFile($file, 'status', $nodes[0][$i][1]);
			$latitude	= $this->findInLocationFile($file, 'latitude', $nodes[0][$i][1]);
			$longitude	= $this->findInLocationFile($file, 'longitude', $nodes[0][$i][1]);
			$interfaces	= $this->findInLocationFile($file, 'interfaces', $nodes[0][$i][1]);
			$masterip	= $this->findInLocationFile($file, 'masterip', $nodes[0][$i][1]);
			$nodetype	= $this->findInLocationFile($file, 'nodetype', $nodes[0][$i][1]);
			$name		= $this->findInLocationFile($file, 'name', $nodes[0][$i][1]);

			$descriptionLocation = 'Naam: ' . $name . '<br/>Locatie: ' . $location . '<br/>Status: ' . $status . '<br/>Latitude: ' . $latitude . '<br/>Longitude: ' . $longitude . '<br/>Interfaces: ' . $interfaces . '<br/>Master IP: ' . $masterip . '<br/>Node type: ' . $nodetype . '<br/><br/>';

			if ($placemarkPosition = $this->getPlacemarkByName($name)) {
				$this->KMLPlacemarks[$placemarkPosition]->setDescriptionLocation($descriptionLocation);
				$this->KMLPlacemarks[$placemarkPosition]->setLongitude($longitude);
				$this->KMLPlacemarks[$placemarkPosition]->setLatitude($latitude);
			} else {
				$placemark = new KMLPlacemark();
				$placemark->setID($name);
				$placemark->setName($name);
				$placemark->setDescriptionLocation($descriptionLocation);
				$placemark->setLongitude($longitude);
				$placemark->setLatitude($latitude);
				$this->addPlacemark($placemark);
			}
		}
	}

	/*
	 * Function: findInLocationFile
	 * Parameters: string $file, string $keyword, integer $offset
	 * Function: Find the $keyword in $file and return the value of $keyword, starting at $offset, on error return false
	 */
	private function findInLocationFile($file, $keyword, $offset) {
		$start = strpos($file, $keyword, $offset) + strlen($keyword . ' = ');
		$end	= strpos($file, "\n", $start);

		if ($start && $end && ($start < $end)) {
			return substr($file, $start, $end - $start);
		} else {
			return false;
		}
	}

	/*
	 * Function: parseStatusFile
	 * Parameters: string $file
	 * Function: Parse the node status file updating or adding KMLPlacemark objects to the current KMLFile object
	 */
	public function parseStatusFile($file) {
		$fileContents = explode("\r\n", $file);

		if ($fileContents[0] != KMLFile::$fileFirst) {
			trigger_log(LOG_WARNING, 'Contents of file do not match with template of first line', __FILE__, __LINE__);
		}

		$linesCount = count($fileContents);
		for ($i = 1; $i < $linesCount - 1; $i++) {
			$lineContent = explode(',', $fileContents[$i]);

			if (count($lineContent) != count($this->fileContent)) {
				trigger_log(LOG_WARNING, 'Contents of file do not match with template of lines', __FILE__, __LINE__);
			}

			// TODO: Process all lines and update KMLPlacemark objects we already have in the current object
			$type = $lineContent[0];
			$host_name = str_replace('CNode', '', $lineContent[1]);
			$has_been_checked = $lineContent[2];
			$check_execution_time = $lineContent[3];
			$current_state = $lineContent[4];
			$last_hard_state = $lineContent[5];
			$last_check = $lineContent[6];
			$problem_has_been_acknowledged = $lineContent[7];

			$descriptionStatus = 'Type: ' . $type . '<br/>Host name: ' . $host_name . '<br/>Has been checked: ' . $has_been_checked . '<br/>Check execution time: ' . $check_execution_time . '<br/>Currenr state: ' . $current_state . '<br/>Last hard state: ' . $last_hard_state . '<br/>Last check: ' . $last_check . '<br/>Problem has been acknowledged: ' . $problem_has_been_acknowledged . '<br/><br/>';

			if ($placemarkPosition = $this->getPlacemarkByName($host_name)) {
				$this->KMLPlacemarks[$placemarkPosition]->setDescriptionStatus($descriptionStatus);
			} else {
				$placemark = new KMLPlacemark();
				$placemark->setID($host_name);
				$placemark->setName($host_name);
				$placemark->setDescriptionStatus($descriptionStatus);
				$this->addPlacemark($placemark);
			}
		}
	}
}
?>