aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/hannibal2/skyhanni/data/ChatClickActionManager.kt
blob: 3dc03c5f954efc6318e11dc29aa522072fd0e8a3 (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
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() {
        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()
    )
}