package com.github.nullptroma.wallenc.usecases

import com.github.nullptroma.wallenc.domain.interfaces.IStorage
import com.github.nullptroma.wallenc.domain.interfaces.IStorageInfo
import com.github.nullptroma.wallenc.domain.interfaces.IUnlockManager
import com.github.nullptroma.wallenc.domain.interfaces.IVault
import com.github.nullptroma.wallenc.domain.interfaces.IVaultsManager
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class RemoveStorageUseCase @Inject constructor(
    private val vaultsManager: IVaultsManager,
    private val unlockManager: IUnlockManager,
    private val manageStoragesEncryptionUseCase: ManageStoragesEncryptionUseCase,
) {

    suspend fun remove(storage: IStorageInfo) {
        if (storage !is IStorage) return

        if (!storage.isVirtualStorage) {
            unlockManager.close(storage)
            findOwningVault(storage.uuid)?.remove(storage)
            return
        }

        val parent = findParentStorage(storage) ?: return
        manageStoragesEncryptionUseCase.clearAndDisableEncryption(parent)
    }

    private fun findOwningVault(storageUuid: UUID): IVault? =
        vaultsManager.vaults.value.firstOrNull { v ->
            v.storages.value.any { it.uuid == storageUuid }
        }

    private fun findParentStorage(storage: IStorage): IStorage? {
        val opened = unlockManager.openedStorages.value
        val parentUuid = opened.entries.firstOrNull { it.value.uuid == storage.uuid }?.key
            ?: return null
        val realParent = vaultsManager.vaults.value
            .flatMap { it.storages.value }
            .firstOrNull { it.uuid == parentUuid }
        return realParent ?: opened[parentUuid]
    }
}
