<?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
 */

/**
 * Simple text
 *
 * This datatype is not editable in backend and only shows the current value in
 * a sly_Form_Text element. Use this if you want to set the value only via API.
 */
class _WV_Datatype_Text extends _WV_Datatype_Base implements WV_IDatatype {
	public function checkParamCompatibility(array $oldParameters, array $newParameters) {
		return true;
	}

	public function getIncompatibilityUpdateStatement(array $oldParameters, array $newParameters) {
		return array();
	}

	public function isValueContained($valueToSearch, $valueFromDatabase, array $params, $filterParams) {
		if ($filterParams & WV_Datatype::FILTER_NOCASE) {
			$valueFromDatabase = mb_strtolower($valueFromDatabase);
			$valueToSearch     = mb_strtolower($valueToSearch);
		}

		if ($filterParams & WV_Datatype::FILTER_EXACTMATCH) return $valueToSearch == $valueFromDatabase;
		else return mb_strpos($valueFromDatabase, $valueToSearch) !== false;
	}

	public function serializeForm(WV_IProperty $property) {
		$multi = $property->isMultilingual();
		$list  = sly_Form_Helper::parseFormValue('property_'.$property->getID().'_value', '', $multi);

		return $list;
	}

	protected function getDefaultParams() {
		return array('css' => '', 'html' => false);
	}

	public function renderForm(sly_Form $form, WV_IProperty $property, $value) {
		if ($property->isMultilingual()) {
			throw new WV_Exception_Datatype('The text datatype cannot be used in multilingual forms (yet).');
		}

		if ($value === false) {
			$value = $property->getDefault();
		}
		else {
			// $value is always given as if this was multilingual
			$value = reset($value);
		}

		$params = $property->getParams();
		extract($this->deserializeParams($params)); // $css, $html

		// Element einrichten

		$text = new sly_Form_Text($property->getTitle(), $value);

		$text->setMultilingual($property->isMultilingual());
		$text->setAttribute('style', $css);
		$text->setIsHTML(!empty($html));

		// Element in Slice einhängen

		WV_Datatype::setHelpTextOnElement($form, $text, $property);
		$form->add($text);
		$form->addHiddenValue('property_'.$property->getID().'_value', $value);
		return $form;
	}
}
