package com.dumpster.cleaner.ui.main

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dumpster.cleaner.SpConstObject.isScoreRated
import com.dumpster.cleaner.SpConstObject.mainPageCount
import com.dumpster.cleaner.bean.FeatureBean.Companion.getFunctionTodayUsed
import com.dumpster.cleaner.bean.FeatureBean.Companion.isTodayUsedFunction
import com.dumpster.cleaner.ui.recyclebin.RecycleBinUtils.getRecycleBinData
import com.dumpster.cleaner.utils.PermissionUtils.areNotificationsEnabled
import com.dumpster.cleaner.utils.PermissionUtils.checkNotificationPermission
import com.dumpster.cleaner.utils.PermissionUtils.checkStorePermission
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.io.File

class MainViewModel : ViewModel() {

    var dialogFlow: MutableStateFlow<String> = MutableStateFlow("")
    var nextShowDialog: Boolean = true

    fun checkDialog(context: Context) {

        if (!nextShowDialog) {
            nextShowDialog = true
            return
        }

        if (!isTodayUsedFunction()) {
            dialogFlow.update { "BatteryDialog" }
            return
        }

        if (!context.checkStorePermission()) {
            dialogFlow.update { "StoreDialog" }
            return
        }

        if (
            !context.checkNotificationPermission() ||
            !context.areNotificationsEnabled()
        ) {
            dialogFlow.update { "NotificationDialog" }
            return
        }



        if (!isScoreRated && mainPageCount > 0 && mainPageCount % 4 == 0L) {
            dialogFlow.update { "RateDialog" }
            return
        }
    }

    var recycleBinFileFlow: MutableStateFlow<List<File>> = MutableStateFlow(listOf())

    fun refreshRecycleBin() = viewModelScope.launch(Dispatchers.IO) {
        recycleBinFileFlow.update { getRecycleBinData() }
    }
}