package com.adealink.weparty.room.chat.viewmodel

import androidx.lifecycle.MutableLiveData
import com.adealink.frame.mvvm.livedata.ExtMutableLiveData
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.room.chat.data.InputAction
import com.adealink.weparty.room.chat.data.InputMachine
import com.adealink.weparty.room.chat.data.InputMachineTransaction
import com.adealink.weparty.room.chat.data.InputState
import kotlinx.coroutines.launch


data class InputState(
    val lastState: InputState,
    val currentState: InputState
)

class InputStateViewModel : BaseViewModel() {

    val inputVisibleLD = ExtMutableLiveData<Boolean>()

    fun notifySoftInputVisible(visible: Boolean) {
        inputVisibleLD.send(visible)
    }


    val transactionLD = ExtMutableLiveData<InputMachineTransaction>()
    val inputStateLD = MutableLiveData<com.adealink.weparty.room.chat.viewmodel.InputState>()
    private val stateMachine: InputMachine =
        InputMachine(
            InputState.STATE_NONE,
            mutableListOf(
                /**
                 * transition to [InputState.STATE_NONE]
                 */
                InputMachineTransaction(
                    "",
                    currentState = InputState.STATE_NONE,
                    action = InputAction.EMPTY_CLICKED,
                    nextState = InputState.STATE_NONE
                ),
            ),
            { transaction ->
                transactionLD.send(transaction)
            },
            { last, current ->
                inputStateLD.send(InputState(last, current))
            }
        )


    /**
     * 参考:InputAction
     */
    fun execute(action: InputAction) {
        viewModelScope.launch {
            stateMachine.execute(action)
        }
    }

    fun registerTransaction(
        page: String,
        currentState: InputState,
        action: InputAction,
        nextState: InputState
    ): InputMachineTransaction {
        return stateMachine.registerTransaction(page, currentState, action, nextState)
    }


}