<?php

namespace Franzz\Spot;
use Franzz\Objects\PhpObject;

/**
 * GPX to GeoJSON Converter
 *
 * To convert a gpx file:
 * 1. Add file <file_name>.gpx to geo/ folder
 * 2. Assign file to project: UPDATE projects SET codename = '<file_name>' WHERE id_project = <id_project>;
 * 3. Load any page
 *
 * To force gpx rebuild:
 * ?a=build_geojson&name=<file_name>
 */
class Converter extends PhpObject {

	public function __construct() {
		parent::__construct(__CLASS__);
	}

	public static function convertToGeoJson($sCodeName) {
		$oGpx = new Gpx($sCodeName);
		$oGeoJson = new GeoJson($sCodeName);

		$oGeoJson->buildTracks($oGpx->getTracks());
		if($oGeoJson->isSimplicationRequired()) $oGeoJson->buildTracks($oGpx->getTracks(), true);
		$oGeoJson->sortOffTracks();
		$oGeoJson->saveFile();

		return [
			'logs' => $oGpx->getLog().'<br />'.$oGeoJson->getLog(),
			'center' => $oGeoJson->getCenter()
		];
	}

	public static function isGeoJsonValid($sCodeName) {
		$sGpxFilePath = Gpx::getBackendFilePath($sCodeName);
		$sGeoJsonFilePath = GeoJson::getBackendFilePath($sCodeName);
		
		//No need to generate if gpx is missing
		return !file_exists($sGpxFilePath) || file_exists($sGeoJsonFilePath) && filemtime($sGeoJsonFilePath) >= filemtime($sGpxFilePath);
	}
}