Files
doneit-web/src/app/services/chat/room.service.ts
T
2022-01-14 10:35:54 +01:00

102 lines
2.5 KiB
TypeScript

import { Injectable } from '@angular/core'
import { WsChatService } from 'src/app/services/chat/ws-chat.service';
import { MessageService } from 'src/app/services/chat/message.service'
import { ChatUserService } from 'src/app/services/chat/chat-user.service'
import { showDateDuration } from 'src/plugin/showDateDuration'
import { ToastsService } from '../toast.service';
import { chatHistory, ChatMessage } from 'src/app/models/chatMethod'
@Injectable({
providedIn: 'root'
})
export class RoomService {
massages: MessageService[] = []
lastMessage: MessageService;
chatUser: ChatUserService[] = []
customFields:any;
id = ''
name = ''
_updatedAt = {}
private hasLoadHistory = false
duration = ''
private ToastService = ToastsService
constructor(
public WsChatService: WsChatService,
private MessageService: MessageService,
) {}
setData({customFields, id, name, lastMessage, _updatedAt}) {
this.customFields = customFields
this.id = id
this.name = name
this.lastMessage = lastMessage
this._updatedAt = _updatedAt
this.calDateDuration()
}
receiveMessage() {
this.WsChatService.receiveLiveMessageFromRoom(
this.id,
(ChatMessage:ChatMessage) => {
ChatMessage = this.fix_updatedAt(ChatMessage)
const message = new MessageService()
message.setData(ChatMessage.result)
this.massages.push(message)
this.calDateDuration(ChatMessage.result._updatedAt)
this.ToastService.presentToast('nova mensagem')
}
)
}
send(msg) {
this.WsChatService.send(this.id, msg)
}
// runs onces only
loadHistory(limit= 100) {
if(this.hasLoadHistory){ return false}
this.WsChatService.loadHistory(this.id, limit).then((chatHistory:chatHistory) => {
console.log('loadHistory', chatHistory)
chatHistory.result.messages.reverse().forEach(message => {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService()
wewMessage.setData(message)
this.massages.push(wewMessage)
});
})
this.hasLoadHistory = true
}
ReactToMessage() {}
private calDateDuration(date = null) {
this.duration = showDateDuration(date || this._updatedAt);
}
private fix_updatedAt(message) {
if(message.result) {
message.result._updatedAt = message.result._updatedAt['$date']
} else{
message._updatedAt = message._updatedAt['$date']
}
return message
}
// to add
countDownDate(){}
}