<?php
/*
 * Copyright (c) 2012, 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
 */

abstract class _WV24_Dbg_Extensions {
	public static function onControllerFound(array $params) {
		$layout = sly_Core::getLayout();
		$nav    = $layout->getNavigation();
		$page   = $nav->get('system', 'system');

		if ($page) {
			$page->addSubpage('realurl2dbg', 'realURL2-Debugger');
		}
	}

	public static function initLayout(array $params) {
		$page = sly_Core::getCurrentControllerName();

		if (!in_array($page, array('structure', 'realurl2dbg')) || !WV24_Util::hasSiteStartArticle()) {
			return $params['subject'];
		}

		$layout = sly_Core::getLayout();
		$prefix = '../data/dyn/public/realurl2/debugger/';

		$layout->addCSSFile($prefix.'backend.css');
		$layout->addJavaScriptFile($prefix.'backend.js');

		if ($page === 'structure') {
			self::injectURLDetails($layout);
		}

		return $params['subject'];
	}

	public static function injectURLDetails(sly_Layout $layout) {
		// select all children categories and articles
		$catID = sly_request('category_id', 'int', 0);
		$cat   = sly_Util_Category::findById($catID);
		$cats  = $cat === null ? sly_Util_Category::getRootCategories() : $cat->getChildren();
		$arts  = $cat === null ? sly_Util_Article::getRootArticles()    : $cat->getArticles();
		$lists = array('articles' => array(), 'categories' => array());

		foreach ($cats as $idx => $c) {
			$id       = $c->getId();
			$name     = $c->getCatname();
			$a        = sly_Util_Article::findById($c->getId(), $c->getClang());
			$fragment = $a->getFragment();
			$skipped  = $a->isSkipped();
			$url      = $a->getUrl();

			$lists['categories'][$id] = compact('id', 'name', 'fragment', 'skipped', 'url');
		}

		foreach ($arts as $idx => $a) {
			$id       = $a->getId();
			$name     = $a->getName();
			$fragment = $a->getFragment();
			$url      = $a->getUrl();

			$lists['articles'][$id] = compact('id', 'name', 'fragment', 'url');
		}

		$lists = json_encode($lists);
		$code  = sprintf(
			'var realurl2Dbg=realurl2Dbg||{};realurl2Dbg.lists = %s;',
			$lists
		);

		$layout->addJavaScript($code);
	}
}
