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

class _WV2_Extensions_Article extends _WV2_Extensions_Base {
	public static function onArticleToStartarticle(array $params) {
		// add metainfos for the new category
		$metainfos = WV2_MetaProvider::getAllCategoryMetaInfos();

		foreach ($metainfos as $name => $metainfo) {
			$metainfos[$name] = $metainfo->getDefault();
		}

		$cat     = (int) $params['subject'];
		$clangs  = sly_Util_Language::findAll(true);
		$service = new _WV2_Service_Metadata();

		foreach ($clangs as $clang) {
			$service->insertObject($cat, $clang, WV2_Metainfo::TYPE_CATEGORY, $metainfos);
		}

		// remove category metadata for old startarticle
		$service->deleteObject($params['old_cat'], WV2_Metainfo::TYPE_CATEGORY);

		// clear cache
		WV2_Metainfo::clearDataCache();
	}

	/**
	 * Handler für ART_META_FORM
	 *
	 * Erzeugt das Frontend-Fomular und hängt es an das Subject an.
	 *
	 * @param  array $params  die von Sally übergebenen Parameter
	 * @return sly_Form       das Formular-Objekt
	 */
	public static function onArticleMetaForm(array $params) {
		if (!self::canView() && !self::canEdit()) return $params['subject'];

		$articleID   = (int) $params['id'];
		$article     = sly_Util_Article::findById($articleID);
		$articleType = $article->getType();
		$isMeta      = sly_Core::getCurrentControllerName() === 'contentmeta';

		$availableInfos = WV2_MetaProvider::getAllArticleMetaInfos($isMeta);
		$assignedData   = WV2_MetaProvider::articleData(null, null, null, $article, true);
		$requiredInfos  = WV2_MetaProvider::getMetaInfosForArticleType($articleType);
		$dataToDisplay  = _WV2_Metainfo::getInfosToDisplay($availableInfos, $isMeta, $assignedData, $requiredInfos);

		$form = $params['subject'];

		$form->addHiddenValue('metainfo', 1);
		$form->addClass('wv2_frontend_'.($isMeta ? 'meta' : 'slice'));
		$form->add(new sly_Form_Fragment('<div class="wv2_frontend_meta">'));

		include _WV2_PATH.'templates/articles/articletype/frontend.phtml';
		include _WV2_PATH.'templates/articles/metainfos.phtml';

		$form->add(new sly_Form_Fragment('</div>'));
		return $form;
	}

	/**
	 * Handler für ART_META_FORM_FIELDSET
	 *
	 * Erzeugt das Frontend-Fomular und hängt es an das Subject an.
	 *
	 * @param  array $params  die von Sally übergebenen Parameter
	 * @return sly_Form       das Formular-Objekt
	 */
	public static function onArticleMetaFieldset(array $params) {
		if (!self::canEdit() || !sly_Util_Language::isMultilingual()) {
			return $params['subject'];
		}

		if (sly_post('wv2_copymetadata', 'boolean')) {
			self::copyData();
		}

		$clang  = (int) $params['clang'];
		$form   = $params['subject'];
		$submit = new sly_Form_Input_Button('submit', 'wv2_copymetadata', t('metainfo_copymetadata'));

		$from = sly_Form_Helper::getLanguageSelect('wv2_copy_from');
		$from->setLabel(t('from_language'));
		$from->setSelected($clang);

		$to = sly_Form_Helper::getLanguageSelect('wv2_copy_to');
		$to->setLabel(t('to_language'));
		$to->setMultiple(true);

		$form->beginFieldset(t('metainfo_copy_between_languages'), '', 2);
		$form->addRow(array($from, $to));
		$form->add(new sly_Form_ButtonBar(compact('submit')));

		return $form;
	}

	private static function copyData() {
		$article     = sly_post('article_id', 'int');
		$sourceLang  = sly_post('wv2_copy_from', 'int');
		$targetLangs = array_unique(sly_postArray('wv2_copy_to', 'int'));

		if (empty($targetLangs)) {
			print sly_Helper_Message::warn(t('no_language_selected'));
			return;
		}

		$service = new _WV2_Service_Metadata();

		foreach ($targetLangs as $targetLang) {
			if ($sourceLang === $targetLang) {
				print sly_Helper_Message::warn(t('metainfo_languages_equal'));
				continue;
			}

			$service->copy(
				array('object_id' => $article, 'clang' => $sourceLang),
				array('object_id' => $article, 'clang' => $targetLang),
				WV2_Metainfo::TYPE_ARTICLE
			);

			print sly_Helper_Message::info(t('metainfo_metadata_copied'));
		}

		WV2_Metainfo::clearDataCache();
	}

	/**
	 * Handler für ART_META_UPDATED
	 *
	 * Serialisiert das Frontend-Formular und gibt beim nächsten Aufruf von
	 * SLY_ART_MESSAGES die ggf. entstandenen Fehler aus.
	 *
	 * @param array $params  die von Sally übergebenen Parameter
	 */
	public static function onArticleMetaUpdated(array $params) {
		if (!self::canEdit()) return;

		$article = (int) $params['id'];
		$isSlice = false;
		$errors  = _WV2_Serializer::processArticleFrontendForm($isSlice, $article);

		if (is_array($errors)) {
			self::showErrors($errors, WV2_Metainfo::TYPE_ARTICLE);
		}
	}

	/**
	 * Handler für SLY_ART_TYPE
	 *
	 * Aktualisiert bei einer Änderung des Artikeltyps die dazugehörigen
	 * Metainfos.
	 *
	 * @param array $params  die von Sally übergebenen Parameter
	 */
	public static function onArticleTypeUpdated(array $params) {
		$article = $params['subject'];
		$oldType = $params['old_type'];
		$newType = $article->getType();
		$article = $article->getId();

		_WV2_Metainfo::updateArticleType($article, $oldType, $newType);

		// if we have a submitted backend form, update the metadata as well

		if (sly_post('metainfo', 'boolean') && self::canEdit()) {
			$errors = _WV2_Serializer::processArticleFrontendForm(true, $article);

			if (is_array($errors)) {
				self::showErrors($errors, WV2_Metainfo::TYPE_ARTICLE);
			}
		}
	}

	/**
	 * Handler für SLY_ART_COPIED
	 *
	 * Kopiert die Metadaten eines Artikels.
	 *
	 * @param array $params  die von Sally übergebenen Parameter
	 */
	public static function onArticleCopied(array $params) {
		$source  = $params['source'];
		$article = $params['subject'];
		$oldID   = $source->getId();
		$newID   = $article->getId();
		$clang   = $article->getClang();

		// Metadaten kopieren
		$service = new _WV2_Service_Metadata();
		$service->copy(
			array('object_id' => $oldID, 'clang' => $clang),
			array('object_id' => $newID, 'clang' => $clang),
			WV2_Metainfo::TYPE_ARTICLE
		);

		// Listen-Cache leeren
		WV2_Metainfo::clearDataCache();
	}

	/**
	 * Handler für SLY_ART_DELETED
	 *
	 * Löscht alle Metadaten für den gelöschten Artikel.
	 *
	 * @param array $params  die von Sally übergebenen Parameter
	 */
	public static function onArticleDeleted(array $params) {
		$service = new _WV2_Service_Metadata();
		$service->deleteArticle($params['subject']);

		WV2_Metainfo::clearDataCache();
	}

	/**
	 * Handler für SLY_ART_ADDED
	 *
	 * @param array $params  die von Sally übergebenen Parameter
	 */
	public static function onArticleAdded(array $params) {
		$type = $params['type'];

		// Wenn ein Artikel ohne Typ angelegt wurde, tue nichts.

		if (empty($type)) {
			return;
		}

		// Standardwerte übernehmen

		$metainfos = WV2_MetaProvider::getMetaInfosForArticleType($type);

		foreach ($metainfos as $name => $metainfo) {
			$metainfos[$name] = $metainfo->getDefault();
		}

		$art     = (int) $params['subject'];
		$clang   = (int) $params['clang'];
		$service = new _WV2_Service_Metadata();

		$service->insertObject($art, $clang, WV2_Metainfo::TYPE_ARTICLE, $metainfos);
	}

	/**
	 * Handler für SLY_ART_UPDATED
	 *
	 * @param array $params  die von Sally übergebenen Parameter
	 */
	public static function onArticleUpdated(array $params) {
		WV2_Metainfo::clearDataCache();
	}

	/**
	 * Handler für SLY_ART_STATUS
	 *
	 * Leert den Datencache. Wichtig für Operationen mit "onlineonly".
	 *
	 * @param array $params  die von Sally übergebenen Parameter
	 */
	public static function onArticleStatus(array $params) {
		WV2_Metainfo::clearDataCache();
	}
}
