package com.secspace.lib.common.function

import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.util.Log
import com.secspace.lib.common.dialog.LoadingDialog
import com.secspace.lib.common.dialog.SwitcherDialog
import com.secspace.lib.common.utils.IntentUtil
import com.secspace.lib.common.utils.Prefs
import com.secspace.lib.common.utils.closeAccessibility
import kotlinx.coroutines.*

class ExitService : Service() {
    private val TAG = "ExitService"
    private var mAppContext: Context? = null
    private var outing = false

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "exit start")
        mAppContext = this

        if (outing)
            return super.onStartCommand(intent, flags, startId)
        outing = true
        LoadingDialog.getInstance(mAppContext).show("切换中")

        GlobalScope.launch(Dispatchers.IO) {
            closeAccessibility(mAppContext as ExitService)
            Prefs.setMdmInitializedWhenEnter(mAppContext, false)
            WorkManager.exit(mAppContext)
            delay(1500)
            withContext(Dispatchers.Main) {
                IntentUtil.startSystemLauncher(mAppContext)
                LoadingDialog.getInstance(mAppContext).dismiss()
                outing = false
                Log.d(TAG, "exit end")
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }
}