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

/**
 * Datentyp "Sally Media Widget"
 *
 * Dieser Datentyp erzeugt ein Sally-Media-Widget.
 *
 * Der vom Datentyp verwaltete Wert ist der Dateiname des ausgewählten Mediums.
 */
class _WV_Datatype_SlyMediaWidget extends _WV_Datatype_Base_MediaWidget implements WV_IDatatype {
	public function renderForm(sly_Form $form, WV_IProperty $property, $value) {
		$value = $this->decodeFormValue($property, $value);
		$btn   = new sly_Form_Widget_Media('property_'.$property->getID().'_value', $property->getTitle(), $value);

		$this->initFormElement($form, $btn, $property);
		$form->add($btn);

		return $form;
	}

	public function serializeFormFilter($list, WV_IProperty $property) {
		$params   = $property->getParams();
		$required = !empty($params['required']);

		foreach ($list as $value) {
			if ($required && empty($value)) throw new WV_Exception_Datatype(t('devutils_datatype_slymediabutton_error'));
		}

		return $list;
	}

	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 deserializeValue($value, array $params) {
		$value = trim($value);
		if (strlen($value) === 0) return null;

		$medium = sly_Util_Medium::findByFilename($value);
		return $medium ? $value : null;
	}

	protected function getDefaultParams() {
		return array(
			'types'      => array(),
			'categories' => array(),
			'recursive'  => false,
			'required'   => false
		);
	}
}
