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

abstract class WV42_Events {
	public static function register() {
		$dispatcher = sly_Core::dispatcher();

		if (sly_Core::isBackend()) {
			$dispatcher->register('SLY_USER_FORM', array(__CLASS__, 'event_sly_user_form'));
		}

		$dispatcher->register('SLY_ADDONS_LOADED', array(__CLASS__, 'event_sly_addons_loaded'));
		$dispatcher->register('SLY_USER_ADDED', array(__CLASS__, 'event_sly_user_edited'));
		$dispatcher->register('SLY_USER_UPDATED', array(__CLASS__, 'event_sly_user_edited'));
		$dispatcher->register('SLY_MODEL_USER_GETROLES', array(__CLASS__, 'event_sly_model_user_getroles'));
		$dispatcher->register('SLY_ART_ADDED', array(__CLASS__, 'event_sly_art_added'));
		$dispatcher->register('SLY_CAT_ADDED', array(__CLASS__, 'event_sly_art_added'));
		$dispatcher->register('SLY_CACHE_CLEARED', array(__CLASS__, 'event_sly_cache_cleared'));
		$dispatcher->register('SLY_SEND_RESPONSE', array(__CLASS__, 'event_output_filter'));
		$dispatcher->register('SLY_DB_IMPORTER_AFTER', array(__CLASS__, 'event_database_import'));
	}

	public static function event_sly_addons_loaded(array $params) {
		if (sly_Core::isBackend()) {
			$user = sly_Util_User::getCurrentUser();

			if ($user && $user->isAdmin()) {
				$page = sly_Core::getLayout()->getNavigation()->get('user', 'system');

				if ($page) {
					$page->addSubpage('user', t('users'));
					$page->addSubpage('rbac', t('rbac'));
				}
			}
		}
	}

	public static function event_sly_model_user_getroles(array $params) {
		$user = $params['object'];

		if (!isset($user->roles)) {
			$pacUser     = new pac_User($user->getID());
			$user->roles = $pacUser->getRoles();
		}

		return $user->roles;
	}

	public static function event_sly_user_form($params) {
		$user = $params['user'];
		$form = $params['subject'];

		$roleService = pac_RoleService::getInstance();
		$curRoles    = array();
		$allRoles    = array();

		foreach ($roleService->getAllRoles() as $role) {
			$allRoles[$role->getId()] = sly_translate($role->getTitle());
		}

		if ($user) {
			$pac_user = new pac_User($user->getId());
			$curRoles = $pac_user->getRoles();
		}

		$roleSelect = new sly_Form_Select_DropDown('rbac_user_roles', t('rbac_user_roles'), $curRoles, $allRoles);
		$roleSelect->setMultiple(true);
		$roleSelect->setSize(5);
		$form->addHiddenValue('rbac_form', '1');
		$form->addElement($roleSelect);

		return $form;
	}

	public static function event_sly_user_edited($params) {
		if (sly_post('rbac_form', 'boolean', false)) {
			$user     = $params['subject'];
			$roles    = sly_postArray('rbac_user_roles', 'int');
			$pac_user = new pac_User($user->getId());
			$pac_user->setRoles($roles);

			WV42_UserCache::delete($user->getId());
		}
	}

	public static function event_sly_art_added($params) {
		$articleId = $params['subject'];
		$re_id     = $params['re_id'];

		// Because this event handler is called once for each language, we have
		// to make sure we dont't accidentally try to insert the rows more than
		// once.

		$db    = sly_DB_Persistence::getInstance();
		$table = pac_Core::ROLES_DESTINATIONS_TABLE;
		$rows  = (int) $db->magicFetch($table, 'COUNT(*)', array(
			'destination' => 'article',
			'value'       => $articleId
		));

		if ($rows === 0) {
			$table     = pac_Core::dbTable($table);
			$statement = pac_Core::prepare(
				'INSERT INTO `'.$table.'` (`destination`, `token`, `role_id`, `value`) '.
				'SELECT `destination`, `token`, `role_id`, :article_id FROM `'.$table.'` WHERE `destination` = :dest AND `value` = :value'
			);

			$statement->execute(array('article_id' => $articleId, 'dest' => 'article', 'value' => $re_id));
		}
	}

	public static function event_sly_cache_cleared($params) {
		WV42_UserCache::flush();
		return $params['subject'];
	}

	public static function event_output_filter($params) {
		WV42_UserCache::persist();
		return $params['subject'];
	}

	public static function event_database_import(array $params) {
		// remove all user<->role associations that point to users not existing in our local DB.

		$table     = pac_Core::dbTable(pac_Core::ROLES_USERS_TABLE);
		$userTable = pac_Core::dbTable('user');
		$statement = pac_Core::prepare(sprintf('DELETE FROM `%s` WHERE user_id NOT IN (SELECT id FROM `%s`)', $table, $userTable));

		$statement->execute();

		return $params['subject'];
	}
}
