1/*
2 * Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16
17import { ChatBox } from './ChatBox';
18import Logger from '../../utils/Logger';
19
20class BasicDataSource implements IDataSource {
21  private listeners: DataChangeListener[] = [];
22
23  public totalCount(): number {
24    return 0;
25  }
26
27  public getData(index: number): ESObject {
28    return undefined;
29  }
30
31  registerDataChangeListener(listener: DataChangeListener): void {
32    if (this.listeners.indexOf(listener) < 0) {
33      Logger.info('add listener');
34      this.listeners.push(listener);
35    }
36  }
37
38  unregisterDataChangeListener(listener: DataChangeListener): void {
39    const pos = this.listeners.indexOf(listener);
40    if (pos >= 0) {
41      Logger.info('remove listener');
42      this.listeners.splice(pos, 1);
43    }
44  }
45
46  notifyDataReload(): void {
47    this.listeners.forEach((listener) => {
48      listener.onDataReloaded();
49    });
50  }
51
52  notifyDataAdd(index: number): void {
53    this.listeners.forEach((listener) => {
54      listener.onDataAdd(index);
55    });
56  }
57
58  notifyDataChange(index: number): void {
59    this.listeners.forEach((listener) => {
60      listener.onDataChange(index);
61    });
62  }
63
64  notifyDataDelete(index: number): void {
65    this.listeners.forEach((listener) => {
66      listener.onDataDelete(index);
67    });
68  }
69
70  notifyDataMove(from: number, to: number): void {
71    this.listeners.forEach((listener) => {
72      listener.onDataMove(from, to);
73    });
74  }
75}
76
77export class ChatSource extends BasicDataSource {
78  private chatsArray: Array<ChatBox> = [];
79
80  public totalCount(): number {
81    return this.chatsArray.length;
82  }
83
84  public getData(index: number): ChatBox {
85    return this.chatsArray[index];
86  }
87
88  public addData(index: number, data: ChatBox): void {
89    this.chatsArray.splice(index, 0, data);
90    this.notifyDataAdd(index);
91  }
92
93  public pushData(data: ChatBox): void {
94    this.chatsArray.push(data);
95    this.notifyDataAdd(this.chatsArray.length - 1);
96  }
97}
98