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

/**
 * Hilfsklasse für das Addon
 *
 * Diese Klasse stellt eine Hand voll Methoden für die einzelnen Module dieses
 * Addons zur Verfügung.
 *
 * Diese Klasse ist nicht als öffentliche API gedacht, dafür gibt es
 * WV2_MetaProvider. Außerhalb des AddOns sollte sie daher *nicht* verwendet
 * werden.
 *
 * @ingroup internal
 */
abstract class _WV2_Metainfo extends WV_Object {
	/**
	 * AddOn initialisieren
	 */
	public static function init(array $params) {
		$page   = $params['name'];
		$active = array('devutilsdocs_metainfo', 'structure', 'content', 'contentmeta', 'mediapool', 'user');

		if (in_array($page, $active)) {
			self::initLayout();
		}
	}

	public static function initLayout() {
		$layout = sly_Core::getLayout();
		$baseA  = sly_Util_AddOn::assetBaseUri('webvariants/metainfo');
		$baseB  = sly_Util_AddOn::assetBaseUri('webvariants/developer-utils');

		$layout->addCSSFile($baseA.'css/metainfo.less');
		$layout->addJavaScriptFile($baseB.'js/jquery.cookie.min.js');
		$layout->addJavaScriptFile($baseB.'js/jquery.wvtogglefieldset.min.js');
		$layout->addJavaScriptFile($baseA.'js/metainfo.min.js');
	}

	public static function addDocPage(array $params) {
		$params['subject'][] = array('devutilsdocs_metainfo', t('metainfo_metainfos'));
		return $params['subject'];
	}

	/**
	 * Hilfsmethode zu den Benutzerrechten
	 *
	 * Diese Methode ermittelt, ob der aktuelle Benutzer das angegebene Recht
	 * hat.
	 *
	 * @param  string $right  das Benutzerrecht (nur MetaInfo-Rechte!)
	 * @return bool           true, wenn das Recht vorhanden ist, sonst false
	 */
	public static function isAllowed($right) {
		$user = sly_Util_User::getCurrentUser();
		return $user && ($user->isAdmin() || $user->hasRight('metainfo', $right));
	}

	/**
	 * Artikeltyp aktualisieren
	 *
	 * @param int    $articleID  die ID des Artikels
	 * @param string $oldType    der alte Artikeltyp
	 * @param string $newType    der neue Artikeltyp
	 */
	public static function updateArticleType($articleID, $oldType, $newType) {
		if ($oldType === $newType) {
			return;
		}

		$articleID    = (int) $articleID;
		$infosOldType = array_keys(WV2_MetaProvider::getMetaInfosForArticleType($oldType));
		$infosNewType = array_keys(WV2_MetaProvider::getMetaInfosForArticleType($newType));
		$service      = new _WV2_Service_Metadata();

		///////////////////////////////////////////////////////////////////////
		// Lösche alle Metadaten von Metainfos, die der neue Typ nicht besitzt

		$infosToDelete = array_diff($infosOldType, $infosNewType);

		if (!empty($infosToDelete)) {
			foreach ($infosToDelete as $idx => $metainfo) {
				$service->delete($articleID, null, WV2_Metainfo::TYPE_ARTICLE, $metainfo);
			}
		}

		///////////////////////////////////////////////////////////////////////
		// add the new metainfo's default value to all articles

		$infosToAdd = array_diff($infosNewType, $infosOldType);
		$languages  = sly_Util_Language::findAll(true);

		foreach ($infosToAdd as $metainfo) {
			$info  = WV2_Metainfo::getMetainfo($metainfo, WV2_Metainfo::TYPE_ARTICLE);
			$value = $info->getDefault();

			foreach ($languages as $clang) {
				$service->insert($articleID, $clang, WV2_Metainfo::TYPE_ARTICLE, $metainfo, $value);
			}
		}

		WV2_Metainfo::clearAllCaches();
		return true;
	}

	public static function getInfosToDisplay(array $available, $isSeparatePage, $assigned, array $required) {
		$return   = array();
		$assigned = sly_makeArray($assigned); // if the object has no metadata yet

		$defaultPos = 1000.001;
		foreach ($available as $name => $info) { /* @var $info _WV2_Info */
			if ($info->getType() === WV2_Metainfo::TYPE_ARTICLE && $info->getMetapage() !== $isSeparatePage) {
				continue;
			}

			if (!$info->getBackend()) {
				continue;
			}

			$value = isset($assigned[$name]) ? $assigned[$name] : null;
			$req   = isset($required[$name]);

			if (!$info->getPosition()) $defaultPos = $defaultPos + 0.001;
			$return[$info->getGroup()][] = array('info' => $info, 'value' => $value, 'required' => $req, 'pos' => !$info->getPosition() ? $defaultPos : $info->getPosition());
		}

		ksort($return, SORT_STRING);

		foreach ($return as $group) usort($group, array(__CLASS__, 'cmp'));

		return $return;
	}

	public static function cmp(array $a, array $b) {
		$a = $a['pos'];
		$b = $b['pos'];

		if ($a == $b) return 0;
		return ($a < $b) ? -1 : 1;
	}
}
