<?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_MediaCategory extends WV42_Renderer_Base {
	private $i      = 1;
	private $destID = 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_MediaCategory::getRootCategories();
		$children = array_merge($all, $rootCats);

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

		// prepare tokens
		$this->destID = $destination->getId();

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

		// wrap in container
		$container = new sly_Form_Container();
		$container->addFormRowClass('rbac-mediacategory-tree');
		$container->setContent($tree);

		// 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');

		// add element
		$form->beginFieldset(t('media_categories'), 'mediacategory');
		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%][%catid%][]" value="access" id="wv42_perm_%dstid%_%catid%" %checked%class="chk-token-access" />
				<label for="wv42_perm_%dstid%_%catid%" class="sly-inline"> %name%</label>
			</div>
			%subtree%
		</li>';

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

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

				++$this->i;

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

				$replacement = !empty($this->dataCache[$id]) ? 'checked="checked" ' : '';
				$curItem     = str_replace('%checked%', $replacement, $curItem);

				$li .= str_replace(
					array('%classes%', '%dstid%', '%catid%', '%name%', '%subtree%'),
					array($classes, $this->destID, $id, $label, $subTree),
					$curItem
				);
			}

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

		return $ul;
	}
}
