All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.pechorina.kairos.automat.builder.AutomatBuilder.kt Maven / Gradle / Ivy

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 }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy