package com.example.studyapp.job

import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.core.app.JobIntentService
import com.example.studyapp.autoJS.AutoJsUtil
import com.example.studyapp.device.ChangeDeviceInfoUtil
import com.example.studyapp.device.LoadDeviceCallback
import com.example.studyapp.proxy.ClashUtil
import com.example.studyapp.update.ChangeCallBack
import com.example.studyapp.update.UpdateUtil.changeDevice
import com.example.studyapp.utils.CountryCode
import com.example.studyapp.utils.IpUtil
import com.example.studyapp.utils.LogFileUtil
import com.example.studyapp.utils.ShellUtils
import org.json.JSONObject
import java.util.Locale

/**
 * 监听任务
 */
interface JobCallback {
    fun onJobFailed()
}
class StartJobService : JobIntentService() {
    override fun onHandleWork(intent: Intent) {
        if (running) {
            return
        }
        setRunning(true)
        exec(
            callback = object : JobCallback {
                override fun onJobFailed() {
                    Handler(Looper.getMainLooper()).postDelayed({
                        onEvent(this@StartJobService)
                    }, 1000 * 10)
                }
            }
        )
    }

    protected fun exec(callback: JobCallback) {
        try {
            ShellUtils.execRootCmdAndGetResult("pm grant com.example.studyapp android.permission.INTERACT_ACROSS_USERS")
            ShellUtils.execRootCmdAndGetResult("pm grant com.example.studyapp android.permission.WRITE_SECURE_SETTINGS")
            ShellUtils.execRootCmdAndGetResult("pm setenforce 0")
            ChangeDeviceInfoUtil.getAddDeviceInfo(
                CountryCode.currentCountry.uppercase(Locale.getDefault()), CountryCode.DEVICE_TYPE,
                object :LoadDeviceCallback{
                    override fun onLoadDeviceInfo(
                        bigoDevice: JSONObject?,
                        afDevice: JSONObject?
                    ) {
//                        ClashUtil.startProxy(applicationContext)
//                        ClashUtil.switchProxyGroup("PROXY", "DIRECT", "http://127.0.0.1:6170")
                        ClashUtil.switchProxyWithPort(CountryCode.switchCountry())
//                        ClashUtil.switchProxyGroup("PROXY", "my-socks5-proxy", "http://127.0.0.1:6170")
                        val geoInfo: String = IpUtil.fetchGeoInfo()
                        val timeZone: String = IpUtil.getTimeZone(geoInfo)
                        changeDevice(packageName, bigoDevice, afDevice,timeZone, object : ChangeCallBack {
                            override fun changeSuccess() {
                                AutoJsUtil.runAutojsScript(applicationContext)
                                setRunning(false)
                            }

                            override fun changeFailed() {
                                LogFileUtil.logAndWrite(
                                    Log.ERROR,
                                    TAG,
                                    "Change device failed",
                                    null
                                )
                                callback.onJobFailed()
                                setRunning(false)
                            }
                        })
                    }

                    override fun onLoadDeviceError(error: String?) {
                        callback.onJobFailed()
                        setRunning(false)
                    }

                })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    companion object {
        private const val TAG = "StartJobService"
        private const val jobId = 101

        private var running = false

        fun onEvent(context: Context) {
            enqueueWork(
                context,
                StartJobService::class.java, jobId, Intent(
                    context,
                    StartJobService::class.java
                )
            )
        }

        fun setRunning(runningV: Boolean) {
            running = runningV
        }
    }
}