aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/hannibal2/skyhanni/data/ChatClickActionManager.kt
blob: 140615e08289ea8392b4ec6236562dfbb9878a74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package at.hannibal2.skyhanni.data

import at.hannibal2.skyhanni.utils.ChatUtils
import at.hannibal2.skyhanni.utils.SimpleTimeMark
import at.hannibal2.skyhanni.utils.StringUtils

object ChatClickActionManager {

    private val actions = mutableListOf<ClickableAction>()

    fun oneTimeClick(message: String, onClick: () -> Any, expiresAt: SimpleTimeMark) {
        val action = ClickableAction(StringUtils.generateRandomId(), message, onClick, expiresAt = expiresAt)
        actions.add(action)
        action.sendToChat()
    }

    private fun ClickableAction.sendToChat() {
        @Suppress("DEPRECATION")
        // TODO rename function
        ChatUtils.clickableChat(message, "shaction $token", prefix = false)
    }

    fun onCommand(args: Array<String>) {
        if (args.size == 1) {
            getActionByToken(args[0])?.runAction()
        }
    }

    private fun ClickableAction.runAction() {
        if (expiresAt.isInPast()) {
            actions.remove(this)
            return
        }
        onClick()
        if (oneTime) {
            actions.remove(this)
        }
    }

    private fun getActionByToken(token: String) = actions.find { it.token == token }

    class ClickableAction(
        val token: String,
        val message: String,
        val onClick: () -> Any,
        val oneTime: Boolean = true,
        val expiresAt: SimpleTimeMark = SimpleTimeMark.farFuture(),
    )
}