<?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 WV42_Renderer_Article extends WV42_Renderer_Base {
	private $i      = 1;
	private $tokens = null;
	private $dest   = null;
	private $role   = null;

	/**
	 * render form
	 *
	 * @param  sly_Form        $form
	 * @param  pac_Role        $role
	 * @param  pac_Destination $destination
	 * @param  array           $destConfig
	 * @return sly_Form
	 */
	public function render(sly_Form $form, pac_Role $role, pac_Destination $destination, array $destConfig) {
		$all      = array(sly_Authorisation_ListProvider::ALL);
		$rootCats = sly_Util_Category::getRootCategories();
		$rootArts = sly_Util_Article::getRootArticles();
		$children = array_merge($all, $rootCats, $rootArts);

		// make sure we don't have to call our database a billion times
		$this->buildCache($role, $destination);

		// prepare tokens
		$tokens = $destConfig['token'];
		$this->tokens = array_keys($tokens);
		$this->dest   = $destination;
		$this->role   = $role;

		foreach ($tokens as $token => $title) {
			$tokens[$token] = sly_translate($title);
		}

		// build tree
		$tree = $this->tree($children, 1);

		// wrap in container
		$content    = t('wv42_content');
		$changeType = t('wv42_change_type');
		$publish    = t('wv42_publish_abbr');
		$move       = t('wv42_move');
		$edit       = t('wv42_edit');
		$container  = new sly_Form_Container();
		$container->addFormRowClass('rbac-article-tree');
		$container->setContent(<<<CONTENT
<p class="header">
	$edit
	<span class="chk inherit">&nbsp;</span>
	<span class="chk">$content</span>
	<span class="chk">$changeType</span>
	<span class="chk">$publish</span>
	<span class="chk">$move</span>
</p>
$tree
CONTENT
);

		// add assets
		sly_Core::getLayout()->addCSSFile(sly_Util_AddOn::assetBaseUri('webvariants/rbac-treeview').'backend.less');
		sly_Core::getLayout()->addJavaScriptFile(sly_Util_AddOn::assetBaseUri('webvariants/rbac-treeview').'backend.js');

		// include magic
		WV42_DestinationFormHelper::writeSuperDeclaration($destination, $destConfig);

		// add element
		$form->beginFieldset(t('structure'), 'article');
		return $form->add($container);
	}

	protected function tree($children, $level = 1) {
		$ul = '';

		static $liFrmt =
		'<li class="%classes%">
			<div class="sly-select-checkbox-list">
				<input type="checkbox" name="wv42_perm[%dstid%][%artid%][]" value="edit" id="wv42_perm_%dstid%_%artid%" %checked-edit%class="chk-token-edit" />
				<label for="wv42_perm_%dstid%_%artid%" class="sly-inline"> %name%</label>
				<span class="chk inherit"><a href="#" class="inheriter" title="%inherit%">&nbsp;</a></span>
				<span class="chk"><input type="checkbox" name="wv42_perm[%dstid%][%artid%][]" value="editcontent" %checked-editcontent%class="chk-token-editcontent" /></span>
				<span class="chk"><input type="checkbox" name="wv42_perm[%dstid%][%artid%][]" value="edittype" %checked-edittype%class="chk-token-edittype" /></span>
				<span class="chk"><input type="checkbox" name="wv42_perm[%dstid%][%artid%][]" value="publish" %checked-publish%class="chk-token-publish" /></span>
				<span class="chk"><input type="checkbox" name="wv42_perm[%dstid%][%artid%][]" value="move" %checked-move%class="chk-token-move" /></span>
			</div>
			%subtree%
		</li>';

		if (is_array($children)) {
			$len = count($children);
			$li  = '';

			foreach ($children as $idx => $cat) {
				$isAll       = $cat === sly_Authorisation_ListProvider::ALL;
				$isArticle   = !$isAll && ($cat instanceof sly_Model_Article);
				$catChildren = $isAll ? array() : ($isArticle ? array() : $cat->getChildren());
				$classes     = array('lvl-'.$level, $this->i % 2 ? 'odd' : 'even');

				if ($isAll) {
					$classes[] = 'is-all';
				}
				elseif (empty($catChildren)) {
					$classes[] = 'leaf';
				}

				++$this->i;

				$subTree = $this->tree($catChildren, $level + 1);
				$classes = implode(' ', $classes);
				$label   = $isAll ? t('all') : ($isArticle ? ($cat->getName().' ('.t('article').')') : $cat->getCatname());
				$label   = sly_html($label);
				$id      = $isAll ? 0 : $cat->getId();
				$curItem = $liFrmt;

				foreach ($this->tokens as $token) {
					$replacement = isset($this->dataCache[$id]) && in_array($token, $this->dataCache[$id]) ? 'checked="checked" ' : '';
					$curItem     = str_replace('%checked-'.$token.'%', $replacement, $curItem);
				}

				$li .= str_replace(
					array('%classes%', '%dstid%', '%artid%', '%name%', '%subtree%', '%inherit%'),
					array($classes, $this->dest->getId(), $id, $label, $subTree, ht('rbac_tv_click_to_inherit_rights')),
					$curItem
				);
			}

			if (!empty($li)) {
				$ul = "<ul>$li</ul>";
			}
		}

		return $ul;
	}
}
