<?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 Link List Widget"
 *
 * Der Datentyp verwaltet eine Liste von Artikel-IDs.
 */
class _WV_Datatype_SlyLinkListWidget extends _WV_Datatype_Base_LinkWidget implements WV_IDatatype {
	public function renderForm(sly_Form $form, WV_IProperty $property, $value) {
		$value = $this->decodeFormValue($property, $value);
		$btn   = new sly_Form_Widget_LinkList('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) {
			if (empty($value)) {
				$articles = array();
			}
			else {
				$articles = explode(',', $value);
				$articles = array_map('intval', $articles);
			}

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

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

		return $list;
	}

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

		$articles = array_filter(array_map('intval', explode(',', $value)));
		$result   = array();

		foreach ($articles as $article) {
			if (sly_Util_Article::exists($article)) $result[] = $article;
		}

		return $result;
	}

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