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.task.TaskUtil
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 org.json.JSONObject
import java.util.Locale
import java.util.UUID

class ScriptJobService : JobIntentService() {

    override fun onHandleWork(intent: Intent) {
        execute(callback = object : JobCallback {
            override fun onJobFailed() {
                Handler(Looper.getMainLooper()).postDelayed({
                    StartJobService.onEvent(applicationContext)
                }, 1000 * 20)
            }
        })
    }

    fun execute(callback: JobCallback) {
        val taskId = UUID.randomUUID().toString()
        runCatching {
            ChangeDeviceInfoUtil.getAddDeviceInfo(
                CountryCode.currentCountry.uppercase(Locale.getDefault()), CountryCode.DEVICE_TYPE,
                object :LoadDeviceCallback {
                    override fun onLoadDeviceInfo(
                        bigoDevice: JSONObject?,
                        afDevice: JSONObject?
                    ) {
//                        ClashUtil.startProxy(applicationContext)
                        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() {
                                runCatching {
                                    AutoJsUtil.runAutojsScript(applicationContext)
                                    TaskUtil.execSaveTask(
                                        applicationContext,
                                        androidId,
                                        taskId,
                                        name,
                                        IpUtil.fetchGeoInfo()
                                    )
                                    TaskUtil.uploadFile(applicationContext, androidId, name)
                                }.onFailure {
                                    callback.onJobFailed()
                                }
                            }

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

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

    companion object {
        private const val TAG = "ScriptJobService"
        private const val jobId = 102
        private const val androidId = "FyZqWrStUvOpKlMn"

        private var name =  ""

        fun onEvent(context: Context, packageName: String) {
            name = packageName
            enqueueWork(
                context,
                ScriptJobService::class.java, jobId, Intent(
                    context,
                    ScriptJobService::class.java
                )
            )
        }
    }
}