<?php
/**
 * @author Andrés Seré <andres@sere.uy>
 *
 */

namespace dokuwiki\plugin\structgeohash\types;

use dokuwiki\plugin\struct\types\AbstractBaseType;
//use dokuwiki\plugin\struct\types\TraitFilterPrefix;
//use dokuwiki\plugin\struct\meta\QueryBuilder;
//use dokuwiki\plugin\struct\meta\QueryBuilderWhere;

class GeoHash extends AbstractBaseType {

	protected $config = array (
		'default' => '69zguzduymzu',
		'urlTMP' => 'https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw',
		'attribution' => 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
    		'mapId' => 'mapbox/streets-v11',
    		'maxZoom' => 18,
	);

	/**
	 * @inheritDoc
	 */
	public function validate($rawvalue) {
		// todo: rise an exception if given an error.
		if(!preg_match('/^[a-z0-9]{12}$/', $rawvalue)) {
			$rawvalue = $this->config['default'];
		}
		return $rawvalue;
	}

	/**
	 * @inheritDoc
	 */
	public function renderValue($value, \Doku_Renderer $R, $mode) {
		if( $mode == 'xhtml' ) {
			$R->doc .= $this->valueEditor('dummy', $value, 0);
		}
		else {
			$R->cdata($value);
		}
		return true;
	}

	/**
	 * @inheritDoc
	 */
	public function valueEditor($name, $rawvalue, $htmlID) {
		if(!preg_match('/^[a-z0-9]{12}$/', $rawvalue)) {
			$rawvalue = $this->config['default'];
		}

		$class = 'struct_' . strtolower($this->getClass());

		$params = array(
			'name' => $name,
			'value' => $rawvalue,
			'class' => $class,
			//'type' => 'geohash',
			'id' => $htmlID,
		);

		$params_div = array(
			'class' => $class.'_map',
			//'type' => 'geohash_map',
			'id' => $htmlID.'_map',
			'data-urlTMP' => $this->config['urlTMP'],
			'data-attribution' => $this->config['attribution'],
    			'data-maxZoom' => $this->config['maxZoom'],
			'data-mapId' => $this->config['mapId'],
		);

		$attributes = buildAttributes($params, true);
		$attributes_div = buildAttributes($params_div, true);
		// When is called from renderValue function, name='dummy';
		// the input field must be disabled.
		if ( $name == 'dummy' )
			return "<input $attributes disabled><div $attributes_div></div>";
		else
			return "<input $attributes><div $attributes_div></div>";
	}

}









