package ptaylor.bdd.errors
{
    import flash.events.Event;
    
    import org.robotlegs.mvcs.Mediator;
    
    import ptaylor.bdd.errors.events.SystemErrorEvent;
    
    /**
     * The behavior for the ISystemErrorUI contract.
     */
    public class SystemErrorUIMediator extends Mediator
    {
        [Inject]public var view:ISystemErrorUI;
        
        override public function onRegister():void
        {
            view.errorAcknowledged.add(onErrorAcknowledged);
            contextView.addEventListener(SystemErrorEvent.SYSTEM_ERROR, onSystemError);
            eventMap.mapListener(eventDispatcher, SystemErrorEvent.SYSTEM_ERROR, whenSystemError, SystemErrorEvent);
        }
        
        override public function onRemove():void
        {
            view.errorAcknowledged.remove(onErrorAcknowledged);
            
            contextView.removeEventListener(SystemErrorEvent.SYSTEM_ERROR, onSystemError);
            
            eventMap.unmapListener(eventDispatcher, SystemErrorEvent.SYSTEM_ERROR, whenSystemError, SystemErrorEvent);
        }
        
        /**
         * Listens on the display list for SystemErrorEvents and routes them to
         * the global event bus.
         */
        private function onSystemError(event:SystemErrorEvent):void
        {
            event.stopPropagation();
            dispatch(event);
        }
        
        /**
         * Listens on the global event bus for SystemErrorEvents and injects
         * them into the UI.
         */
        private function whenSystemError(event:SystemErrorEvent):void
        {
            view.handleError(event);
        }
        
        private function onErrorAcknowledged():void
        {
            //Do something when an error has been acknowledged by the user.
            trace('System error acknowledged');
        }
    }
}