import { Injectable , NgZone, ViewChild} from '@angular/core';
import {  NavParams } from 'ionic-angular';
import { Content } from 'ionic-angular';
import { Storage } from '@ionic/storage';
declare var apiRTC: any;

@Injectable()
export class Chatservice {   

	@ViewChild(Content) content: Content;
	
	webRTCClient;
   	myCallId;
    reg_data:any;
   	imClient:any;
   	allMessages = {messages  : '',doctor : ''};
   	txt_msg:any;
   	patientId:any;
   	srcId:any;
   	conv_id:string;
   	convHistory=[];
    patient_conv_id= [];
    convhis= [];
   	public ionScroll;
	obj={};
	
	constructor(private zone: NgZone,public storage:Storage) {
	 
		this.storage.get('reg_data').then((reg_data) => {
			this.reg_data=reg_data;
			apiRTC.jsLoaded = false;
			this.srcId=this.reg_data.id+12;
			this.InitializeApiRTC(); 
		})
		
	}
	
	InitializeApiRTC() {
		//apiRTC initialization
		apiRTC.init({
			apiKey : "819abef1fde1c833e0601ec6dd4a8226",
			apiCCId : this.srcId,
			onReady: (e) => {
				this.sessionReadyHandler(e);
			}
		});
	}
	  
	sessionReadyHandler(e){ 
		 
		this.imClient = apiRTC.session.createIMClient('im68568846015');
		this.myCallId = apiRTC.session.apiCCId;   
		console.log('sessionReady');		
		apiRTC.session.getConversationList();
		
		apiRTC.addEventListener("receiveIMMessage", e=>{
			console.log("new message")
			 var list=this.imClient.getConversationHistory(this.conv_id);
			 apiRTC.session.getConversationList();
		});
		
		apiRTC.addEventListener("channelEvent", e=>{
			//console.log(e)
		});	
	
		apiRTC.addEventListener("receiveConversationHistory", e=>{
			 
			var i;
			var len;
			var histry= e.detail.convHistory;
			//console.log(this.convHistory);
			if(this.convHistory != undefined && this.convHistory.length >0 ){
				for (  i=0, len=histry.length; i < len; i++ ){
					 
					this.obj[histry[i].date] = histry[i];
					}
					console.log(this.obj)
				for ( var key in this.obj )
					this.convHistory.push(this.obj[key]);
					
			}else{
				this.convHistory = e.detail.convHistory;
			}
		}); 
				 

		apiRTC.addEventListener("receiveConversationList", e => {
			 
			var i;
			this.convHistory = [];
			for (i=e.detail.convList.length-1;i>-1;i--) {
				//console.log(e.detail.convList[i].destId, this.patientId);
				//if(parseInt(e.detail.convList[i].destId) == parseInt(this.patientId)){
					this.imClient.getConversationHistory(e.detail.convList[i].convId);
				//}
			} 
		}); 
		  
        apiRTC.addEventListener("updatePresence", e=>{
			//console.log('updatePresenceHandler :' + JSON.stringify(e.detail.connectedUsersList));
        });  
			 
	}
	
	receiveConversationListHandler(e) {
		//console.log('e receiveConversationListHandler = ', e);
	}
	
	send_msg(msg,patient_id){
		
		patient_id = patient_id+123456789;
		console.log(patient_id);
		if(msg != '' || msg != null){
			
			var msgg =this.imClient.sendMessage(patient_id,msg); 
			var d = new Date(); var n = d.getMilliseconds();
			var msg_obj = {'date':d, 'dst': patient_id,'message': msg, 'src' : this.srcId,'srcNickname' : this.srcId}
			this.convHistory.push(msg_obj);
			
		}
	}
	
	receiveIMMessageHandler(e) {
	console.log("new message")
		//var list=this.imClient.getConversationHistory(this.conv_id);
		//apiRTC.session.getConversationList();		
	}
	 
	get_history(patientId){
		this.convHistory = [];
		this.patientId = patientId;
		this.patientId = patientId+123456789;
		console.log(this.patientId);
		apiRTC.session.getConversationList();
	}

}