package com.ujuad.demo.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.ujuad.demo.model.DemoSetting
import com.ujuad.demo.model.NetworkState
import com.ujuad.demo.utils.DemoLogUtils
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.onEach

/**
 * 应用主ViewModel，用于管理SDK初始化状态和全局应用配置
 */
class AppViewModel(application: Application) : AndroidViewModel(application) {
    // SDK初始化状态
    val sdkInitialized = MutableStateFlow(false)

    // 全局配置
    val appConfig = MutableStateFlow<DemoSetting?>(null)

    // 网络状态
    val networkState = MutableStateFlow<NetworkState>(NetworkState.Available)

    init {
        // 记录ViewModel初始化
        DemoLogUtils.i("AppViewModel初始化")

        // 监听SDK初始化状态变化
        sdkInitialized.onEach {
            if (it) {
                DemoLogUtils.i("SDK初始化成功")
            } else {
                DemoLogUtils.i("SDK未初始化")
            }
        }

        // 监听应用配置变化
        appConfig.onEach {
            if (it != null) {
                DemoLogUtils.i("应用配置已加载: $it")
            } else {
                DemoLogUtils.i("应用配置为空")
            }
        }

        // 监听网络状态变化
        networkState.onEach {
            DemoLogUtils.i("网络状态变化: $it")
        }
    }

    /**
     * ViewModel工厂类
     */
    class Factory(private val application: Application) : ViewModelProvider.Factory {
        @Suppress("UNCHECKED_CAST")
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            if (modelClass.isAssignableFrom(AppViewModel::class.java)) {
                return AppViewModel(application) as T
            }
            throw IllegalArgumentException("Unknown ViewModel class")
        }
    }

    companion object {
        private const val TAG = "AppViewModel"
    }
}
