<?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 sly_Controller_Devutilsdocs_Metainfo extends sly_Controller_Devutilsdocs {
	protected function getViewFolder() {
		return _WV2_PATH.'templates/';
	}

	public function indexAction() {
		$this->init();
		$metainfos = $this->collectMetainfos();
		$this->render('documentation.phtml', compact('metainfos'), false);
	}

	protected function collectMetainfos() {
		$metainfos   = array();
		$typeService = sly_Service_Factory::getArticleTypeService();
		$allTypes    = count($typeService->getArticleTypes());
		$types       = array(
			WV2_Metainfo::TYPE_ARTICLE  => t('articles'),
			WV2_Metainfo::TYPE_CATEGORY => t('categories'),
			WV2_Metainfo::TYPE_MEDIUM   => t('media'),
			WV2_Metainfo::TYPE_USER     => t('users')
		);

		foreach ($types as $type => $name) {
			$list             = WV2_MetaProvider::getAllObjectMetaInfos($type);
			$metainfos[$type] = array('title' => $name, 'infos' => array());

			foreach ($list as $metainfoName => $metainfo) {
				$description = $metainfo->getData('description', $metainfo->getHelpText());
				$atypes      = $metainfo->getArticleTypes();

				if (empty($description)) {
					$description = '<'.t('metainfo_no_description').'>';
				}

				if ($metainfo->getType() !== WV2_Metainfo::TYPE_ARTICLE) {
					$atypes = null;
				}
				if (count($atypes) === $allTypes) {
					$atypes = array('<'.t('all').'>');
				}
				elseif ($atypes) {
					foreach ($atypes as $idx => $typeName) {
						$atypes[$idx] = sly_translate($typeService->getTitle($typeName));
					}
				}

				$metainfos[$type]['infos'][$metainfoName] = array(
					'title'       => $metainfo->getTitle(),
					'description' => $description,
					'types'       => $atypes,
					'metapage'    => $metainfo->getMetapage()
				);
			}

			if (empty($metainfos[$type]['infos'])) {
				unset($metainfos[$type]);
			}
			else {
				uasort($metainfos[$type]['infos'], array($this, 'sortHelper'));
			}
		}

		return $metainfos;
	}

	public function sortHelper($elA, $elB) {
		return strnatcasecmp($elA['title'], $elB['title']);
	}

	public function checkPermission($action) {
		return sly_Util_User::getCurrentUser() !== null;
	}
}
