package llc.arma.ble.app.ui.screen.rotation.delete

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import llc.arma.ble.app.ui.common.BaseViewModel
import llc.arma.ble.domain.usecase.DeleteRotationsBySerial
import javax.inject.Inject


@HiltViewModel
class RotationDeleteViewModel @Inject constructor(
    private val savedStateHandle: SavedStateHandle,
    private val deleteRotationsBySerial: DeleteRotationsBySerial
) : BaseViewModel<RotationDeleteContract.State, RotationDeleteContract.Event, RotationDeleteContract.Effect>() {

    override fun setInitialState() = RotationDeleteContract.State

    override fun handleEvents(event: RotationDeleteContract.Event) {
        when(event){
            is RotationDeleteContract.Event.OnDelete -> reduce(viewState.value, event)
            is RotationDeleteContract.Event.OnNavigateUp -> reduce(viewState.value, event)
        }
    }


    private fun reduce(
        state: RotationDeleteContract.State,
        event: RotationDeleteContract.Event.OnNavigateUp
    ) {

        setEffect {

            RotationDeleteContract.Effect.Navigation.NavigateUp

        }

    }

    private fun reduce(
        state: RotationDeleteContract.State,
        event: RotationDeleteContract.Event.OnDelete
    ) {

        viewModelScope.launch {

            deleteRotationsBySerial(savedStateHandle.get<String>("serial")!!)

        }

        setEffect {

            RotationDeleteContract.Effect.Navigation.NavigateUp

        }

    }

}