<?php
/**
 * Example Activation
 *
 * Activation class for Example plugin.
 * This is optional, and is required only if you want to perform tasks when your plugin is activated/deactivated.
 *
 * @package  Bemmelhor
 * @author   Fabricio S Costa <fabriciojf@gmail.com>
 * 
 * @link     http://www.bemmelhor.org
 */
class ExampleActivation {

/**
 * onActivate will be called if this returns true
 *
 * @param  object $controller Controller
 * @return boolean
 */
	public function beforeActivation(&$controller) {
		return true;
	}

/**
 * Called after activating the plugin in ExtensionsPluginsController::admin_toggle()
 *
 * @param object $controller Controller
 * @return void
 */
	public function onActivation(&$controller) {
		// ACL: set ACOs with permissions
		$controller->Bemmelhor->addAco('Example'); // ExampleController
		$controller->Bemmelhor->addAco('Example/admin_index'); // ExampleController::admin_index()
		$controller->Bemmelhor->addAco('Example/index', array('registered', 'public')); // ExampleController::index()

		// Main menu: add an Example link
		$mainMenu = $controller->Link->Menu->findByAlias('main');
		$controller->Link->Behaviors->attach('Tree', array(
			'scope' => array(
				'Link.menu_id' => $mainMenu['Menu']['id'],
			),
		));
		$controller->Link->save(array(
			'menu_id' => $mainMenu['Menu']['id'],
			'title' => 'Example',
			'link' => 'plugin:example/controller:example/action:index',
			'status' => 1,
			'class' => 'example',
		));
	}

/**
 * onDeactivate will be called if this returns true
 *
 * @param  object $controller Controller
 * @return boolean
 */
	public function beforeDeactivation(&$controller) {
		return true;
	}

/**
 * Called after deactivating the plugin in ExtensionsPluginsController::admin_toggle()
 *
 * @param object $controller Controller
 * @return void
 */
	public function onDeactivation(&$controller) {
		// ACL: remove ACOs with permissions
		$controller->Bemmelhor->removeAco('Example'); // ExampleController ACO and it's actions will be removed

		// Main menu: delete Example link
		$link = $controller->Link->find('first', array(
			'conditions' => array(
				'Menu.alias' => 'main',
				'Link.link' => 'plugin:example/controller:example/action:index',
			),
		));
		if (empty($link)) {
			return;
		}
		$controller->Link->Behaviors->attach('Tree', array(
			'scope' => array(
				'Link.menu_id' => $link['Link']['menu_id'],
			),
		));
		if (isset($link['Link']['id'])) {
			$controller->Link->delete($link['Link']['id']);
		}
	}
}
