<?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 "Datum & Zeit"
 */
class _WV_Datatype_DateTime extends _WV_Datatype_Base implements WV_IDatatype {
	public function renderForm(sly_Form $form, WV_IProperty $property, $value) {
		$value    = $this->decodeFormValue($property, $value);
		$style    = $property->getParams();
		$withTime = !empty($style['withtime']);
		$required = !empty($style['required']);

		$datetime = new sly_Form_DateTime('property_'.$property->getID().'_value', $property->getTitle(), $value, null, $withTime);
		$datetime->setMultilingual($property->isMultilingual());
		if ($required) $datetime->setRequired(true);

		if (!empty($style['hide'])) $datetime->addFormRowClass('hide');

		WV_Datatype::setHelpTextOnElement($form, $datetime, $property);
		$form->add($datetime);

		return $form;
	}

	protected function getDefaultParams() {
		return array('withtime' => false);
	}

	public function serializeValue($value, array $params) {
		if (array_key_exists('strtotime', $params) && $params['strtotime']) {
			if ($value === null || !is_scalar($value) || strlen($value) === 0)
				return '';
			if (ctype_digit((string) $value))
				return $value;
			$time = strtotime($value);
			if ($time === false) return '';

			return $time;
		}

		return $value;
	}

	public function deserializeValue($value, array $params) {
		// only the empty string means 'not given', 0 can actually mean a valid date!
		return $value === '' || $value === null ? null : (int) $value;
	}

	public function serializeFormFilter($list, WV_IProperty $property) {
		foreach ($list as $idx => $value) {
			$tstamp = $value === '' ? '' : strtotime($value);

			if ($tstamp === false) {
				throw new WV_Exception_Datatype('Cannot convert from string to time ('.$value.').');
			}

			$list[$idx] = $tstamp;
		}

		return $list;
	}
}
