<?php
/*
 * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

class WV_Property implements WV_IProperty {
	protected $name;          ///< string   der interne Name
	protected $title;         ///< string   der angezeigte Name (Titel)
	protected $datatype;      ///< int      die Datentyp-ID
	protected $params;        ///< string   die Datentyp-Parameter
	protected $default;       ///< string   der Standardwert der Metainformation
	protected $helptext;      ///< string   der Hilfetext
	protected $multilingual;  ///< boolean  mehrsprachig?
	protected $data;          ///< array    weitere Daten

	/**
	 * Konstruktor
	 */
	public function __construct($name, array $data) {
		if (!isset($data['title'])) {
			throw new Exception('Properties require a title.');
		}

		if (!isset($data['datatype'])) {
			throw new Exception('Properties require a datatype.');
		}

		$this->data         = $data;
		$this->name         = trim($name);
		$this->title        = trim($data['title']);
		$this->datatype     = $data['datatype'];
		$this->params       = $this->getData('params', array());
		$this->default      = $this->getData('default', null);
		$this->helptext     = $this->getData('helptext', '');
		$this->multilingual = $this->getData('multilingual', false);

		unset($this->data['title'], $this->data['datatype']);
		unset($this->data['params'], $this->data['default'], $this->data['helptext'], $this->data['multilingual']);
	}

	public function getName()        { return $this->name;          }
	public function getTitle()       { return $this->title;         }
	public function getDatatype()    { return $this->datatype;      }
	public function getParams()      { return $this->params;        }
	public function getDefault()     { return $this->default;       }
	public function getHelpText()    { return $this->helptext;      }
	public function isMultilingual() { return $this->multilingual;  }
	public function isMonolingual()  { return !$this->multilingual; }

	public function getData($key, $default = null) {
		return isset($this->data[$key]) ? $this->data[$key] : $default;
	}

	public function datatypeCall($method, $params = null) {
		$params = sly_makeArray($params);
		return WV_Datatype::call($this->datatype, $method, $params);
	}

	public function deserialize($raw) {
		return $this->datatypeCall('deserializeValue', array($raw, $this->getParams()));
	}

	public function serialize($raw) {
		return $this->datatypeCall('serializeValue', array($raw, $this->getParams()));
	}

	public function renderForm(sly_Form $form, array $values) {
		return $this->datatypeCall('renderForm', array($form, $this, $values));
	}

	public function serializeForm() {
		return $this->datatypeCall('serializeForm', $this);
	}
}
