import { Subscription } from "rxjs/Rx" ; /**
 * Defines an interface that represents a handler function for an interaction.
 * These functions return a value (either null or a value of type TOutput) upon handling the
 * interaction, or undefined if the handler is not able to handle the interaction.
 */ export interface IReactiveInteractionHandler < TInput , TOutput > { ( param ) : TOutput | Promise < TOutput > ; } /**
 * Defines a class that represents an interaction.
 * Interactions are designed to provide a means of resolving view-specific input mechanisms that occur
 * during an operation that a ReactiveObject is performing.
 */ export class ReactiveInteraction < TInput , TOutput > { private _handlerChain : IReactiveInteractionHandler < TInput , TOutput > [ ] = [ ] ; param handler public registerHandler ( handler ) { if ( ! handler ) throw Error ( "Null or undefined handlers cannot be registered. Pass in a valid handler function to properly register it." ) ; this . _handlerChain . unshift ( handler ) ; return new Subscription ( ( ) => { var index = this . _handlerChain . indexOf ( handler ) ; if ( index >= 0 ) { this . _handlerChain . splice ( index , 1 ) ; } } ) ; } param param public handle ( param ? ) { return new Promise < TOutput > ( ( resolve , reject ) => { var currentHandler = 0 ; do { var handler = this . _handlerChain [ currentHandler ] ; try { var result = handler ( param ) ; if ( typeof result !== "undefined" ) { if ( result instanceof Promise ) { ( < Promise < TOutput > > result ) . then ( value => { resolve ( value ) ; } , err => { reject ( err ) ; } ) ; } else { resolve ( result ) ; } return ; } } catch ( err ) { reject ( err ) ; } } while ( ++ currentHandler < this . _handlerChain . length ) ; reject ( new Error ( "No handler handled the interaction. Make sure that registerHandler is being called and that its returned subscription is not being disposed." ) ) ; } ) ; } }