import { Component , OnInit } from '@angular/core' ; import { NavController , PopoverController , ModalController , AlertController } from 'ionic-angular' ; import { MeteorObservable } from 'meteor-rxjs' ; import * as Moment from 'moment' ; import { Observable , Subscriber } from 'rxjs' ; import { Chats , Messages , Users , Pictures } from '../../../../imports/collections' ; import { Chat , Message } from '../../../../imports/models' ; import { ChatsOptionsComponent } from './chats-options' ; import { MessagesPage } from '../messages/messages' ; import template from './chats.html' ; import { NewChatComponent } from './new-chat' ; @ Component ( { template } ) export class ChatsPage implements OnInit { chats ; senderId : string ; constructor ( private navCtrl , private popoverCtrl , private modalCtrl , private alertCtrl ) { this . senderId = Meteor . userId ( ) ; } ngOnInit ( ) { MeteorObservable . subscribe ( 'chats' ) . subscribe ( ( ) => { MeteorObservable . autorun ( ) . subscribe ( ( ) => { this . chats = this . findChats ( ) ; } ) ; } ) ; } addChat ( ) { const modal = this . modalCtrl . create ( NewChatComponent ) ; modal . present ( ) ; } findChats ( ) { return Chats . find ( ) . map ( chats => { chats . forEach ( chat => { chat . title = '' ; chat . picture = '' ; const receiverId = chat . memberIds . find ( memberId => memberId !== this . senderId ) ; const receiver = Users . findOne ( receiverId ) ; if ( receiver ) { chat . title = receiver . profile . name ; chat . picture = Pictures . getPictureUrl ( receiver . profile . pictureId ) ; } this . findLastChatMessage ( chat . _id ) . subscribe ( ( message ) => { chat . lastMessage = message ; } ) ; } ) ; return chats ; } ) ; } findLastChatMessage ( chatId ) { return Observable . create ( ( observer ) => { const chatExists = ( ) => ! ! Chats . findOne ( chatId ) ; MeteorObservable . autorun ( ) . takeWhile ( chatExists ) . subscribe ( ( ) => { Messages . find ( { chatId } , { sort : { createdAt : - 1 } } ) . subscribe ( { next : ( messages ) => { if ( ! messages . length ) { return ; } const lastMessage = messages [ 0 ] ; observer . next ( lastMessage ) ; } , error : ( e ) => { observer . error ( e ) ; } , complete : ( ) => { observer . complete ( ) ; } } ) ; } ) ; } ) ; } showMessages ( chat ) { this . navCtrl . push ( MessagesPage , { chat } ) ; } removeChat ( chat ) { MeteorObservable . call ( 'removeChat' , chat . _id ) . subscribe ( { error : ( e ) => { if ( e ) { this . handleError ( e ) ; } } } ) ; } handleError ( e ) { console . error ( e ) ; const alert = this . alertCtrl . create ( { buttons : [ 'OK' ] , message : e . message , title : 'Oops!' } ) ; alert . present ( ) ; } showOptions ( ) { const popover = this . popoverCtrl . create ( ChatsOptionsComponent , { } , { cssClass : 'options-popover chats-options-popover' } ) ; popover . present ( ) ; } }