'use strict' ; import { IRootScope } from 'teambition' ; import { RestAPI } from '../index' ; declare let Consumer ; export interface IConsumer { _join ( roomId , consumerId ) : void ; join ( roomId ) : angular . IPromise < any > ; onmessage ( eventName , callback ) ; } let joined = [ ] ; let listener = { } ; export const ngConsumer = angular . module ( 'teambition' ) . factory ( 'ngConsumer' , [ '$rootScope' , 'RestAPI' , ( $rootScope , RestAPI ) => { let consumer = new Consumer ( ) ; let join = consumer . join ; let fireListener = ( listeners , result ) => { if ( ! listeners || ! listeners . length ) { return ; } for ( let index = 0 ; index < listeners . length ; index ++ ) { let _listener = listeners [ index ] ; if ( typeof _listener === 'function' ) { _listener ( result ) ; } } if ( ! $rootScope . $$phase ) { $rootScope . $digest ( ) ; } } ; consumer . _join = ( _id , consumerId ) => { if ( ! _id ) { return ; } return RestAPI . save ( { Type : 'projects' , Id : _id , Path1 : 'subscribe' } , { consumerId : consumerId } ) ; } ; consumer . join = ( _id ) => { if ( joined . indexOf ( _id ) === - 1 ) { join . call ( consumer , _id ) ; joined . push ( _id ) ; } } ; consumer . onmessage = ( event , callback ) => { console . log ( event ) ; if ( ! event ) { return ; } if ( typeof event === 'string' ) { if ( typeof callback === 'function' ) { if ( listener [ event ] && listener [ event ] . length ) { if ( listener [ event ] . indexOf ( callback ) === - 1 ) { listener [ event ] . push ( callback ) ; } } else { listener [ event ] = [ callback ] ; } } } else { const params = event . data ? event . data . params : '' ; const results = [ ] ; if ( params instanceof Array ) { angular . forEach ( params , ( data , index ) => { const result = JSON . parse ( data ) ; const e = result . e ; const d = result . d ; const socketParams = e . split ( '/' ) ; const namespace = socketParams [ 0 ] ; if ( e . indexOf ( 'message' ) !== - 1 && typeof d === 'object' ) { const _id = e . split ( '/' ) [ 1 ] ; d . msgId = _id ; fireListener ( listener [ namespace ] , d ) ; } else if ( namespace . indexOf ( 'new' ) !== - 1 && namespace . indexOf ( 'activities' ) === - 1 ) { fireListener ( listener [ namespace ] , d ) ; } else { fireListener ( listener [ e ] , d ) ; } } ) ; } if ( results . length ) { console . log ( 'results: ' , results ) ; } } } ; return consumer ; } ] ) ;