<?php

class TracksController extends Controller
{

	function __construct()
	{
		if (!App::$user->id) {
			App::redirect('/');
		}

		self::$layout = 'layouts/page.php';
		self::addStyle('/css/style.css?ver=' . App::getConfig('version'));
		self::addStyle('/css/pageStyle.css?ver=' . App::getConfig('version'));
		self::addScript('/js/jquery-2.1.0.min.js');
		self::addScript('/js/jquery-ui-1.10.4.custom.min.js');
		self::addScript('/js/bootstrap.min.js');
		self::addStyle('/css/bootstrap.min.css');
		self::addStyle('/css/bootstrap-theme.min.css');
	}

	function actionIndex()
	{
		$trips = Trips::model()->getAll(array('where' => '`owner` = ?'), array(App::$user->id));

		self::render('/tracks/index.php', array(
			'trips' => $trips,
		));
	}

	function actionEdit()
	{
		self::addScript('/js/leaflet.js');
		self::addStyle('/css/leaflet.css');

		self::addScript('/js/editTrack.js');
		self::addStyle('/css/editTrack.css');

		$id = intval(App::getParam('id'));

		if (!$id) {
			App::error404();
		}

		$trip = Trips::model()->getByPK($id);

		if ($trip->isEmpty() || $trip->owner != App::$user->id) {
			App::error404();
		}

		self::render('/tracks/edit.php', array(
			'trip' => $trip,
			'tracks' => Tracks::model()->getAll(array('where' => '`tripId` = ' . $trip->id)),
			'waypoints' => WayPoints::model()->getAll(array('where' => '`tripId` = ' . $trip->id)),
		));
	}


	function actionFiles()
	{
		$files = TrackFiles::model()->getAll(array('where' => '`owner` = :owner'), array('owner' => App::$user->id));

		self::render('/tracks/files.php', array(
			'files' => $files,
		));
	}

	function actionUploadfile()
	{
		$temp = pathinfo($_FILES['file']['name']);
		$filename = $_FILES['file']['name'];
		$extension = strtolower($temp['extension']);
		$uploaddir = App::getBasedir() . 'tracks/';

		$supportedExtensions = array(TrackFiles::FORMAT_GPX, TrackFiles::FORMAT_KML, TrackFiles::FORMAT_KMZ);

		if (!in_array(strtoupper($extension), $supportedExtensions)) {
			App::error404('Неизвестный тип');
		}

		$tmp = TrackFiles::model()->add(array(
			'owner' => App::$user->id,
			'name' => 'Трек ' . date('d-m-Y H:i:s'),
			'filename' => $filename,
			'format' => strtoupper($extension),
			'createdAt' => date('c'),
		));

		$newName = 'track' . $tmp->id . '.' . $extension;
		if (!move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $newName)) {
			App::error404();
		}

		App::redirect('/tracks/import/id/' . $tmp->id);
	}

	function actionGetFile()
	{
		$id = intval(App::getParam('id'));

		if (!$id) {
			App::error404();
		}

		$trackFile = TrackFiles::model()->getByPK($id);

		if ($trackFile->isEmpty() || $trackFile->owner != App::$user->id) {
			App::error404();
		}

		self::renderPartial('file.php', array(
			'filePath' => App::getBasedir() . 'tracks/track' . $id . '.' . strtolower($trackFile->format),
			'fileName' => $trackFile->filename,
		));
	}

	function actionExport()
	{
		$id = intval(App::getParam('id'));
		$trip = Trips::model()->getByPK($id);

		if ($trip->isEmpty() || $trip->owner != App::$user->id) {
			App::error404();
		}

		self::renderPartial('/tracks/gpx.php', array(
			'trip' => $trip,
			'waypoints' => WayPoints::model()->getAll(array('where' => '`tripId` = ?'), array($trip->id)),
			'tracks' => Tracks::model()->getAll(array('where' => '`tripId` = ?'), array($trip->id)),
		));
	}

	function actionImport()
	{
		$id = (int) App::getParam('id');

		if (!$id) {
			App::error404();
		}

		$trackFile = TrackFiles::model()->getByPK($id);

		if ($trackFile->isEmpty() || $trackFile->owner != App::$user->id) {
			App::error404();
		}

		switch ($trackFile->format) {
			case TrackFiles::FORMAT_GPX:
				self::importGpx($trackFile);
				break;
			case TrackFiles::FORMAT_KML:
			case TrackFiles::FORMAT_KMZ:
				self::importKml($trackFile);
				break;
			default:
				App::error404();
				break;
		}

		App::redirect('/tracks');
	}

	private static function importGpx($trackFile)
	{
		$gpx = file_get_contents(App::getBasedir() . 'tracks/track' . $trackFile->id . '.' . strtolower($trackFile->format));
		$gpx = str_replace('geotracker:meta', 'geotrackerMeta', $gpx);
		$gpxObject = simplexml_load_string($gpx);
		unset($gpx);

		$trip = Trips::model()->add(
				array(
					'name' => isset($gpxObject->metadata->name) ? (string) $gpxObject->metadata->name : 'Track',
					'createdAt' => isset($gpxObject->metadata->time) ? $gpxObject->metadata->time : date('c'),
					'owner' => App::$user->id,
					'distance' => 0,
					'description' => 'Трек создан ' . date('d-m-Y H:i') . ' из файла ' . $trackFile->filename,
					'status' => Trips::STATUS_PRIVATE,
				)
		);

		$distance = 0;
		$wayPoints = array();
		$tracks = array();
		$latlngs = array();
		$tracksCounter = 1;
		$tracksCount = $tptCount = $wptCount = 0;

		foreach ($gpxObject as $key => $block) {
			if ($key == 'wpt') {
				if (empty($block)) {
					continue;
				}

				$wayPoint = WayPoints::model()->add(
						array(
							'tripId' => $trip->id,
							'lat' => floatval($block['lat']),
							'lng' => floatval($block['lon']),
							'alt' => isset($block->ele) ? floatval($block->ele) : 0,
							'createdAt' => $block->time,
							'name' => (string) $block->name,
							'description' => (string) $block->desc,
						)
				);

				$wptCount++;
			}

			if ($key == 'trk') {
				if (empty($block->trkseg)) {
					continue;
				}

				foreach ($block->trkseg as $trkpt) {
					if ($trkpt) {
						$track = Tracks::model()->add(
								array(
									'tripId' => $trip->id,
									'name' => (string) $block->name ? (string) $block->name : 'Фрагмент трека №' . $tracksCounter,
									'distance' => 0,
									'description' => '',
								)
						);
						$distanceTmp = 0;
						$prevPoint = array();
						$tracksCounter++;
						$trackPoints = array();

						foreach ($trkpt as $tpt) {
							$speed = isset($tpt->extensions->geotrackerMeta['s']) ? floatval($tpt->extensions->geotrackerMeta['s']) : 0;
							$alt = isset($tpt->ele) ? floatval($tpt->ele) : 0;
							$trackPoint = TrackPoints::model()->add(
									array(
										'trackId' => $track->id,
										'lat' => floatval($tpt['lat']),
										'lng' => floatval($tpt['lon']),
										'alt' => $alt,
										'createdAt' => isset($tpt->time) ? $tpt->time : date('c'),
										'speed' => $speed,
									)
							);

							if ($prevPoint) {
								$distanceTmp += Geo::distance($prevPoint, array('lat' => floatval($tpt['lat']), 'lng' => floatval($tpt['lon']), 'alt' => $alt));
							}

							$prevPoint = array(
								'lat' => floatval($tpt['lat']),
								'lng' => floatval($tpt['lon']),
							);
							if (isset($tpt->ele)) {
								$prevPoint['alt'] = floatval($tpt->ele);
							}
							$tptCount++;
						}

						$distance += $distanceTmp;
						$track->distance = $distanceTmp;
						$track->save();
					}
				}
				$tracksCount++;
			}
		}

		$trip->distance = $distance;
		$trip->save();

		$trackFile->tracksCount = $tracksCount;
		$trackFile->tptCount = $tptCount;
		$trackFile->wptCount = $wptCount;
		$trackFile->distance = $distance;
		$trackFile->save();
	}

	private static function importKml($trackFile)
	{
		$kml = new Kml(App::getBasedir() . 'tracks/track' . $trackFile->id . '.' . strtolower($trackFile->format));


		$trip = Trips::model()->add(
				array(
					'name' => $kml->getName(),
					'createdAt' => $kml->getTime(),
					'owner' => App::$user->id,
					'distance' => 0,
					'description' => 'Трек создан ' . date('d-m-Y H:i') . ' из файла ' . $trackFile->filename,
					'status' => Trips::STATUS_PRIVATE,
				)
		);

		$distance = 0;
		$tracksCounter = 1;
		$tracksCount = $tptCount = $wptCount = 0;

		foreach ($kml->getWaypoints() as $wpt) {
			$wayPoint = WayPoints::model()->add(
					array(
						'tripId' => $trip->id,
						'lat' => floatval($wpt['latlng']['lat']),
						'lng' => floatval($wpt['latlng']['lng']),
						'alt' => floatval($wpt['latlng']['alt']),
						'speed' => 0,
						'createdAt' => $wpt['when'],
						'name' => (string) $wpt['name'],
						'description' => (string) $wpt['description'],
					)
			);

			$wptCount++;
		}

		foreach ($kml->getTracks() as $trackPart) {
			if ($trackPart) {
				$track = Tracks::model()->add(
						array(
							'tripId' => $trip->id,
							'name' => $trackPart['name'] ? $trackPart['name'] : 'Фрагмент трека №' . $tracksCounter,
							'distance' => 0,
							'description' => $trackPart['description'],
						)
				);

				$distanceTmp = 0;
				$prevPoint = array();
				$tracksCounter++;
				$trackPoints = array();

				foreach ($trackPart['latlng'] as $tpt) {
					$trackPoint = TrackPoints::model()->add(
							array(
								'trackId' => $track->id,
								'lat' => floatval($tpt['lat']),
								'lng' => floatval($tpt['lng']),
								'alt' => floatval($tpt['alt']),
								'createdAt' => 0,
								'speed' => 0,
							)
					);

					if ($prevPoint) {
						$distanceTmp += Geo::distance($prevPoint, array('lat' => floatval($tpt['lat']), 'lng' => floatval($tpt['lng'])));
					}

					$prevPoint = array(
						'lat' => floatval($tpt['lat']),
						'lng' => floatval($tpt['lng']),
					);
					$tptCount++;
				}

				$distance += $distanceTmp;
				$track->distance = $distanceTmp;
				$track->save();
			}
		}


		$trip->distance = $distance;
		$trip->save();

		$trackFile->tracksCount = count($kml->getTracks());
		$trackFile->tptCount = $tptCount;
		$trackFile->wptCount = $wptCount;
		$trackFile->distance = $distance;
		$trackFile->save();
	}

}
