import { Injectable } from '@angular/core';
import { localstoreService } from '../localstore.service'
import { SHA1 }  from  'crypto-js'

@Injectable({
  providedIn: 'root'
})
export class ChatMessageService {

  private _message = [] 
  // local storage keyName
  private keyName: string;

  constructor() {

    this.keyName = (SHA1('chat'+this.constructor.name)).toString()

    setTimeout(()=> {
      let restore = localstoreService.get(this.keyName, {})
      this._message = restore.message || {}
    }, 10)

  }

  get message() {
    return this._message
  }
  
  getMessages(roomId) {
    return this._message[roomId] || []
  }

  add(roomId:string, message: any[]) {
    this._message[roomId] = message

    setTimeout(()=> {
      localstoreService.set(this.keyName, {
        message: this._message
      })
    }, 10)
  }

}


export const ChatMessageStore = new ChatMessageService()