<?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 Widget"
 *
 * Dieser Datentyp erzeugt ein Sally-Link-Widget.
 *
 * Der vom Datentyp verwaltete Wert ist die Artikel-ID, die auch beim
 * Deserialisieren zurückgegeben wird.
 */
class _WV_Datatype_SlyLinkWidget 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_Link('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 $idx => $value) {
			if ($required && empty($value)) {
				throw new WV_Exception_Datatype(t('devutils_datatype_slylinkbutton_error'));
			}

			$list[$idx] = strval($value > 0 ? $value : -1);
		}

		return $list;
	}

	public function deserializeValue($value, array $params) {
		$value = (int) $value;
		return ($value <= 0 || !sly_Util_Article::exists($value)) ? null : $value;
	}

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