import { MessageModel } from './MessageModel'

export class MessageListDataSource implements IDataSource {
  private dataArray: MessageModel[] = []
  private listeners: DataChangeListener[] = []

  unregisterDataChangeListener(listener: DataChangeListener): void {
    const pos = this.listeners.indexOf(listener)
    if (pos >= 0) {
      this.listeners.splice(pos, 1)
    }
  }

  registerDataChangeListener(listener: DataChangeListener): void {
    if (this.listeners.indexOf(listener) < 0) {
      this.listeners.push(listener)
    }
  }

  getData(index: number) {
    return this.dataArray[index]
  }

  totalCount(): number {
    return this.dataArray.length
  }

  addData(item: MessageModel) {
    this.dataArray.push(item)
    this.notifyDataAdd(this.dataArray.length - 1)
  }

  addDatas(items: MessageModel[]) {
    this.dataArray.concat(items)
    this.notifyDataAdd(this.dataArray.length - 1)
  }

  notifyDataAdd(index: number): void {
    this.listeners.forEach(listener => {
      listener.onDataAdd(index)
    })
  }

  deleteData(index: number, count: number) {
    this.dataArray.splice(index, count)
    this.notifyDataDelete(this.dataArray.length - 1)
  }

  notifyDataDelete(index: number): void {
    this.listeners.forEach(listener => {
      listener.onDataDelete(index)
    })
  }

}