package com.zxhy.solarmasterace.datastore

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "file_count")

val DUP_IMAGE_COUNTER_KEY = intPreferencesKey("dup_image_counter")
val LARGE_FILES_COUNTER_KEY = intPreferencesKey("large_files_counter")
val EMPTY_FILE_COUNTER_KEY = intPreferencesKey("empty_file_counter")

suspend fun Context.saveFileCount(key: Preferences.Key<Int>, count: Int) {
    dataStore.edit {
        when (key) {
            DUP_IMAGE_COUNTER_KEY -> it[DUP_IMAGE_COUNTER_KEY] = count
            LARGE_FILES_COUNTER_KEY -> it[LARGE_FILES_COUNTER_KEY] = count
            EMPTY_FILE_COUNTER_KEY -> it[EMPTY_FILE_COUNTER_KEY] = count
        }
    }
}

suspend fun Context.queryFileCount(key: Preferences.Key<Int>, action: (count: Int) -> Unit) {
    val flow = when (key) {
        DUP_IMAGE_COUNTER_KEY -> dataStore.data.map { it[DUP_IMAGE_COUNTER_KEY] }
        LARGE_FILES_COUNTER_KEY -> dataStore.data.map { it[LARGE_FILES_COUNTER_KEY] }
        EMPTY_FILE_COUNTER_KEY -> {
            dataStore.data.map { it[EMPTY_FILE_COUNTER_KEY] }
        }

        else -> flowOf(0)
    }
    flow.collect {
        if (it != null) {
            action.invoke(it)
        }
    }

}