<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/

/**
 * Class Francis_Core_EventHandler
 */
class Francis_Core_EventHandler {

    private static $instance = NULL;

    private function __construct() {}
    private function __clone() {}

    private $listeners = array();
    private $isActive = true;

    /**
     * Get singleton instance
     *
     * @return Francis_Core_EventHandler|null
     */
    public static function get() {
        if ( is_null( self::$instance ) ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * Enables event processing
     */
    public function enable() {
        $this->isActive = true;
    }

    /**
     * Disables event processing
     */
    public function disable() {
        $this->isActive = false;
    }

    /**
     * Trigger an event
     *
     * @param string $name  Name of the event
     * @param array $data
     */
    public function trigger( $name, array $data = array() ) {
        if ( $this->isActive && array_key_exists( $name, $this->listeners ) && is_array( $this->listeners[ $name ] ) ) {
            foreach( $this->listeners[ $name ] as $listener ) {
                try {
                    call_user_func( $listener, $data );
                } catch( Exception $e ) {
                    TB_Server_Utils_Log::get()->log( $e );
                }
            }
        }
    }

    /**
     * Add event listener
     * @param string $name  Name of the event
     * @param string $listener  Name of the static function to call
     */
    public function addListener( $name, $listener) {
        if ( !array_key_exists( $name, $this->listeners ) ) {
            $this->listeners[ $name ] = array();
        }

        $this->listeners[ $name ][] = $listener;
    }

    /**
     * Remove listener
     *
     * @param string $name
     * @param string $listener
     */
    public function removeListener( $name, $listener ) {
        if ( array_key_exists( $name, $this->listeners ) &&
             is_array( $this->listeners[ $name ] ) &&
             isset( $this->listeners[ $name ][ $listener ] ) ) {
            unset( $this->listeners[ $name ][$listener ] );
        }
    }

} 