import { Component , OnInit } from '@angular/core' ; import { AlertController , ViewController } from 'ionic-angular' ; import { MeteorObservable } from 'meteor-rxjs' ; import { _ } from 'meteor/underscore' ; import { Observable , Subscription , BehaviorSubject } from 'rxjs' ; import { Chats , Pictures , Users } from '../../../../imports/collections' ; import { User } from '../../../../imports/models' ; import template from './new-chat.html' ; @ Component ( { template } ) export class NewChatComponent implements OnInit { searchPattern : BehaviorSubject < any > ; senderId : string ; users : Observable < User [ ] > ; usersSubscription : Subscription ; constructor ( private alertCtrl , private viewCtrl ) { this . senderId = Meteor . userId ( ) ; this . searchPattern = new BehaviorSubject ( undefined ) ; } ngOnInit ( ) { this . observeSearchBar ( ) ; } updateSubscription ( newValue ) { this . searchPattern . next ( newValue ) ; } observeSearchBar ( ) { this . searchPattern . asObservable ( ) . debounce ( ( ) => Observable . timer ( 1000 ) ) . forEach ( ( ) => { if ( this . usersSubscription ) { this . usersSubscription . unsubscribe ( ) ; } this . usersSubscription = this . subscribeUsers ( ) ; } ) ; } addChat ( user ) { MeteorObservable . call ( 'addChat' , user . _id ) . subscribe ( { next : ( ) => { this . viewCtrl . dismiss ( ) ; } , error : ( e ) => { this . viewCtrl . dismiss ( ) . then ( ( ) => { this . handleError ( e ) ; } ) ; } } ) ; } subscribeUsers ( ) { const subscription = MeteorObservable . subscribe ( 'users' , this . searchPattern . getValue ( ) ) ; const autorun = MeteorObservable . autorun ( ) ; return Observable . merge ( subscription , autorun ) . subscribe ( ( ) => { this . users = this . findUsers ( ) ; } ) ; } findUsers ( ) { return Chats . find ( { memberIds : this . senderId } , { fields : { memberIds : 1 } } ) . startWith ( [ ] ) . mergeMap ( ( chats ) => { const receiverIds = _ . chain ( chats ) . pluck ( 'memberIds' ) . flatten ( ) . concat ( this . senderId ) . value ( ) ; return Users . find ( { _id : { $nin : receiverIds } } ) . startWith ( [ ] ) ; } ) ; } handleError ( e ) { console . error ( e ) ; const alert = this . alertCtrl . create ( { buttons : [ 'OK' ] , message : e . message , title : 'Oops!' } ) ; alert . present ( ) ; } getPic ( pictureId ) { return Pictures . getPictureUrl ( pictureId ) ; } }