package com.github.nullptroma.wallenc.ui.screens.main.screens.storage.secrets

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import com.github.nullptroma.wallenc.domain.errors.WallencException
import com.github.nullptroma.wallenc.ui.ViewModelBase
import com.github.nullptroma.wallenc.ui.resources.toUserNotification
import com.github.nullptroma.wallenc.ui.screens.main.screens.storage.requireStorageUuid
import com.github.nullptroma.wallenc.usecases.FindStorageUseCase
import com.github.nullptroma.wallenc.usecases.ManageTextSecretsUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class TextSecretsViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle,
    private val findStorageUseCase: FindStorageUseCase,
    private val manageTextSecretsUseCase: ManageTextSecretsUseCase,
) : ViewModelBase<TextSecretsScreenState>(TextSecretsScreenState()) {

    private val storageUuid = savedStateHandle.requireStorageUuid()

    init {
        observeSecrets()
    }

    private fun observeSecrets() {
        viewModelScope.launch {
            val storage = findStorageUseCase.find(storageUuid)
            if (storage == null) {
                updateState(
                    state.value.copy(
                        isLoading = false,
                        errorNotification = WallencException.Feature.StorageNotFound().toUserNotification(),
                    ),
                )
                return@launch
            }
            if (storage.metaInfo.value.encInfo != null && !storage.isVirtualStorage) {
                updateState(
                    state.value.copy(
                        isLoading = false,
                        isAvailable = false,
                        errorNotification = WallencException.Feature.NeedsDecryptedView().toUserNotification(),
                    ),
                )
                return@launch
            }
            combine(
                storage.isAvailable,
                manageTextSecretsUseCase.observe(storage),
            ) { available, items ->
                state.value.copy(
                    isLoading = false,
                    isAvailable = available,
                    items = items,
                    errorNotification = null,
                )
            }.collect { ui ->
                updateState(ui)
            }
        }
    }
}
