1 /*
<lambda>null2  * Copyright (C) 2019 The Android Open Source Project
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 package com.example.android.bubbles.data
17 
18 typealias ChatThreadListener = (List<Message>) -> Unit
19 
20 class Chat(val contact: Contact) {
21 
22     private val listeners = mutableListOf<ChatThreadListener>()
23 
24     private val _messages = mutableListOf(
25         Message(1L, contact.id, "Send me a message", null, System.currentTimeMillis()),
26         Message(2L, contact.id, "I will reply in 5 seconds", null, System.currentTimeMillis())
27     )
28     val messages: List<Message>
29         get() = _messages
30 
31     fun addListener(listener: ChatThreadListener) {
32         listeners.add(listener)
33     }
34 
35     fun removeListener(listener: ChatThreadListener) {
36         listeners.remove(listener)
37     }
38 
39     fun addMessage(builder: Message.Builder) {
40         builder.id = _messages.last().id + 1
41         _messages.add(builder.build())
42         listeners.forEach { listener -> listener(_messages) }
43     }
44 }
45