1
0
mirror of https://github.com/InsanusMokrassar/TelegramBotAPI.git synced 2024-06-03 00:15:27 +00:00
tgbotapi/tgbotapi.behaviour_builder.fsm/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/behaviour_builder/BehaviourWithFSMStateHandlerHolder.kt

48 lines
2.0 KiB
Kotlin
Raw Normal View History

2021-10-13 08:22:01 +00:00
package dev.inmo.tgbotapi.extensions.behaviour_builder
import dev.inmo.micro_utils.fsm.common.*
import kotlin.reflect.KClass
/**
* Special holder for [BehaviourContextWithFSM]. This holder helps [BehaviourContextWithFSM] to understand whether it
* can handle input [State] with [delegateTo] or not
*
* @param inputKlass This [KClass] will be used to compare input [State] type and declare ability of [delegateTo] to
* handle incoming [State]. See [checkHandleable] for more info
* @param strict This flag will be used in [checkHandleable] to choose strategy of checking incoming [State]
* @param delegateTo This handler will be called in case [checkHandleable] returns true with class caster incoming
* [State] in [handleState]
*/
2021-11-06 15:21:49 +00:00
class BehaviourWithFSMStateHandlerHolder<I : O, O : State>(
2021-10-13 08:22:01 +00:00
private val inputKlass: KClass<I>,
private val strict: Boolean = false,
2021-11-06 15:21:49 +00:00
private val delegateTo: BehaviourWithFSMStateHandler<I, O>
2022-05-10 20:47:00 +00:00
) : CheckableHandlerHolder<O, O>, BehaviourWithFSMStateHandler<O, O> {
2021-10-13 08:22:01 +00:00
/**
* Check ability of [delegateTo] to handle this [state]
*
* @return When [state]::class exactly equals to [inputKlass] will always return true. Otherwise when [strict]
* mode is disabled, will be used [KClass.isInstance] of [inputKlass] for checking
*/
2022-05-10 20:47:00 +00:00
override suspend fun checkHandleable(state: O): Boolean = state::class == inputKlass || (!strict && inputKlass.isInstance(state))
2021-10-13 08:22:01 +00:00
/**
* Handling of state :)
*/
2022-05-10 20:47:00 +00:00
override suspend fun BehaviourContextWithFSM<in O>.handleState(state: O): O? = with(delegateTo) {
2022-05-08 20:27:06 +00:00
@Suppress("UNCHECKED_CAST")
2022-05-03 17:12:03 +00:00
handleState(state as I)
2021-10-13 08:22:01 +00:00
}
2022-05-10 20:47:00 +00:00
override suspend fun StatesMachine<in O>.handleState(state: O): O? = if (this is BehaviourContextWithFSM) {
handleState(state)
} else {
null
}
2021-10-13 08:22:01 +00:00
}
2021-11-06 15:21:49 +00:00
inline fun <reified I : O, O : State> BehaviourWithFSMStateHandlerHolder(
strict: Boolean = false,
delegateTo: BehaviourWithFSMStateHandler<I, O>
) = BehaviourWithFSMStateHandlerHolder(I::class, strict, delegateTo)