package com.remax.visualnovel.app.initializer.impl

import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Build
import android.webkit.WebView
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.ProcessLifecycleOwner
import com.remax.visualnovel.app.ProcessLifecycleObserver
import com.remax.visualnovel.app.initializer.AppInitializers
import com.remax.visualnovel.app.initializer.di.AppInitializerPriority
import com.remax.visualnovel.app.viewmodel.AppGlobalViewModel

/**
 * Created by HJW on 2023/5/11
 * 系统相关初始化
 */
class SystemInitializer(val application: Application, val appGlobalViewModel: AppGlobalViewModel) : AppInitializers {

    override fun init() {
        //监听application生命周期
        ProcessLifecycleOwner.get().lifecycle.addObserver(ProcessLifecycleObserver)
        ProcessLifecycleObserver.setAppGlobalViewModel(appGlobalViewModel)
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
        //启用矢量图兼容
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            var processName = ""
            (application.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager)
                ?.runningAppProcesses
                ?.asSequence()
                ?.forEach { processInfo ->
                    if (processInfo.pid == android.os.Process.myPid()) {
                        processName = processInfo.processName
                    }
                }
            if (processName != application.packageName) {
                WebView.setDataDirectorySuffix(processName)
            }
        }
    }

    override fun widget(): Int {
        return AppInitializerPriority.SERIES_2.priority
    }
}