<?php

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

class Map extends PhpObject {

	const MAP_TABLE = 'maps';
	const MAPPING_TABLE = 'mappings';

	private Db $oDb;
	private $asMaps;

	public function __construct(Db &$oDb) {
		parent::__construct(__CLASS__);
		$this->oDb = &$oDb;
		$this->asMaps = array();
    }

	private function setMaps() {
		$asMaps = $this->oDb->selectRows(array('from'=>self::MAP_TABLE));
		foreach($asMaps as $asMap) $this->asMaps[$asMap['codename']] = $asMap;
	}

	private function getMaps($sCodeName='') {
		if(empty($this->asMaps)) $this->setMaps();
		return ($sCodeName=='')?$this->asMaps:$this->asMaps[$sCodeName];
	}

	public function getProjectMaps($iProjectId) {
		$asMappings = $this->oDb->selectRows(
			array(
				'select'	=> array(Db::getId(self::MAP_TABLE), 'default_map'),
				'from'		=> self::MAPPING_TABLE,
				'constraint'=> array("IFNULL(id_project, {$iProjectId})" => $iProjectId)
			),
			Db::getId(self::MAP_TABLE)
		);
		
		$asProjectMaps = array();
		foreach($this->getMaps() as $asMap) {
			if(array_key_exists($asMap['id_map'], $asMappings)) {
				$asMap['default_map'] = $asMappings[$asMap['id_map']];
				$asProjectMaps[] = $asMap;
			}
		}

		return $asProjectMaps;
	}

	public function getMapUrl($sCodeName, $asParams) {
		$asMap = $this->getMaps($sCodeName);
		$asParams['token'] = $asMap['token'];
		return self::populateParams($asMap['pattern'], $asParams);
	}

	private static function populateParams($sUrl, $asParams) {
		foreach($asParams as $sParam=>$sValue) {
			$sUrl = str_replace('{'.$sParam.'}', $sValue, $sUrl);
		}

		return $sUrl;
	}
}