<?php

namespace Franzz\Spot;
use Franzz\Objects\ToolBox;

class Gpx extends Geo {

	const EXT = '.gpx';

	public function __construct($sCodeName) {
		parent::__construct($sCodeName);
		$this->parseFile();
	}

	public function getTracks() {
		return $this->asTracks;
	}

	private function parseFile() {
		$this->addNotice('Parsing: '.$this->sFilePath);
		if(!file_exists($this->sFilePath)) $this->addError($this->sFilePath.' file missing');
		else {
			$oXml = simplexml_load_file($this->sFilePath);

			//Tracks
			$this->addNotice('Converting  '.count($oXml->trk).' tracks');
			foreach($oXml->trk as $aoTrack) {
				$asTrack = array(
					'name'	=> (string) $aoTrack->name,
					'desc'	=> str_replace("\n", '', ToolBox::fixEOL((strip_tags($aoTrack->desc)))),
					'cmt'	=> ToolBox::fixEOL((strip_tags($aoTrack->cmt))),
					'color'	=> (string) $aoTrack->extensions->children('gpxx', true)->TrackExtension->DisplayColor,
					'points'=> array()
				);

				foreach($aoTrack->trkseg as $asSegment) {
					foreach($asSegment as $asPoint) {
						$asTrack['points'][] = array(
							'lon' => (float) $asPoint['lon'],
							'lat' => (float) $asPoint['lat'],
							'ele' => (int) $asPoint->ele
						);
					}
				}
				$this->asTracks[] = $asTrack;
			}

			//Waypoints
			$this->addNotice('Ignoring '.count($oXml->wpt).' waypoints');
		}
	}
}