
net.pechorina.kairos.automat.builder.AutomatBuilder.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kairos-automat Show documentation
Show all versions of kairos-automat Show documentation
Kairos Automat is a finite-state machine library
The newest version!
package net.pechorina.kairos.automat.builder
import net.pechorina.kairos.automat.Automat
import net.pechorina.kairos.automat.State
import net.pechorina.kairos.automat.SyncAutomat
import net.pechorina.kairos.automat.listeners.LoggingListener
class AutomatBuilder {
private var configurer: AutomatConfigurer = AutomatConfigurer(this)
private val states: MutableSet> = mutableSetOf()
private val stateFinder = { payload: S -> findState(payload) }
fun withConfig(): AutomatConfigurer {
return configurer
}
fun build(): Automat {
states.addAll(
configurer.getStates()
)
configurer.getChildParentPairs(stateFinder).forEach {
val childState: State = it.first
val parentState: State = it.second
childState.parent = parentState
}
configurer.getTransitions(stateFinder).forEach {
val sourceState: State = it.source
val existingTransitions = sourceState.transitions
sourceState.transitions = existingTransitions + it
}
if (!hasInitialState()) throw RuntimeException("Initial state is not defined")
val machine: Automat = SyncAutomat(states, configurer.id, configurer.name)
if (configurer.logging) machine.addListener(LoggingListener(machine))
return machine
}
private fun findState(payload: S): State {
return states.find { it.value == payload } ?: throw RuntimeException("State[$payload] not found")
}
private fun hasInitialState(): Boolean {
return this.states.any { it.initialState }
}
}