<?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 List Widget"
 *
 * Dieser Datentyp erzeugt ein Sally-MediaList-Widget.
 *
 * Der vom Datentyp verwaltete Wert ist eine Liste von ausgewählten Dateien
 * (array von Strings).
 */
class _WV_Datatype_SlyMediaListWidget extends _WV_Datatype_Base_MediaWidget implements WV_IDatatype {
	public function renderForm(sly_Form $form, WV_IProperty $property, $value) {
		$value = $this->decodeFormValue($property, $value);

		if ($property->isMultilingual()) {
			foreach ($value as $clang => $clangVal) {
				$value[$clang] = str_replace('|', ',', $clangVal);
			}
		}
		else {
			$value = str_replace('|', ',', $value);
		}

		$btn = new sly_Form_Widget_MediaList('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 = $this->deserializeParams($property->getParams());
		$min    = isset($params['min']) ? $params['min'] : 0;
		$max    = isset($params['max']) ? $params['max'] : 0;

		foreach ($list as $idx => $value) {
			$media = array_filter(explode(',', $value));

			if (count($media) < $min)             throw new WV_Exception_Datatype(t('devutils_datatype_select_too_few', $min));
			if (count($media) > $max && $max > 0) throw new WV_Exception_Datatype(t('devutils_datatype_select_too_many', $max));

			$list[$idx] = implode(',', $media);
		}

		return $list;
	}

	public function deserializeValue($value, array $params) {
		if (empty($value)) return array();

		$sep    = mb_strpos($value, '|') === false ? ',' : '|'; // for BC
		$files  = array_filter(explode($sep, $value));
		$result = array();

		foreach ($files as $filename) {
			if (sly_Util_Medium::findByFilename($filename)) $result[] = $filename;
		}

		return $result;
	}

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

		$sep      = mb_strpos($valueFromDatabase, '|') === false ? ',' : '|'; // for BC
		$elements = explode($sep, $valueFromDatabase);
		$yes      = false;

		foreach ($elements as $element) {
			if ($filterParams & WV_Datatype::FILTER_EXACTMATCH) $yes = $valueToSearch == $element;
			else $yes = mb_strpos($element, $valueToSearch) !== false;

			if ($yes) return true;
		}

		return false;
	}

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