package com.cake.draw.painting.environment

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.RemoteException
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.ad.click.cp.IMyAidlCallback
import com.ad.click.cp.IMyAidlInterface
import com.cake.draw.painting.environment.hy.TimeoutManager
import com.cake.draw.painting.environment.hy.TimeoutTask

class AIDLClient private constructor() {
    private var connection: ServiceConnection? = null
    private var myService: IMyAidlInterface? = null
    private var isClicking = false // 防止重复执行点击
    private var isReset = false // 防止重复执行重置
    private var isBound = false  // 记录是否已绑定
    var isChangeComplete = false//防止修改参数重复发送

    // LiveData 让 Activity 监听回调
    val paramCompleteLiveData = MutableLiveData<Boolean>()

    //连接是否断开
    val connectCompleteLiveData = MutableLiveData<Boolean>()

    val clickAdCompleteLiveData = MutableLiveData<Boolean>()

    companion object {
        val instance: AIDLClient by lazy { AIDLClient() }
    }

    /**
     * 1. 初始化服务连接
     */
    fun initConnection() {
        connection = object : ServiceConnection {
            override fun onServiceConnected(className: ComponentName?, service: IBinder?) {
                myService = IMyAidlInterface.Stub.asInterface(service)
                myService?.registerCallback(callback)
                isBound = true
                connectCompleteLiveData.postValue(true)
                Log.d("ocean-brush", "CP控制器连接成功")
            }

            override fun onServiceDisconnected(className: ComponentName?) {
                myService = null
                isBound = false
                connectCompleteLiveData.postValue(false)
                Log.d("ocean-brush", "CP控制器连接断开")
            }
        }
    }

    /**
     * 绑定 AIDL
     */
    fun connectService(context: Context): Boolean {
        var success = false
        if (!isBound) {
            val intent = Intent()
            intent.setAction("com.ad.click.cp.AidlService")//必须与服务端指定的service的name一致
            intent.setPackage("com.vastness.mask")//这个包名必须写服务端APP的包名
            success = context.bindService(intent, connection!!, Context.BIND_AUTO_CREATE)
        } else {
            Log.d("ocean-brush", "AIDL 已绑定，无需重复绑定")
        }
        return success
    }

    /**
     * 解绑 AIDL
     */
    fun disconnect(context: Context) {
        if (isBound && connection != null) {
            context.unbindService(connection!!)
            isBound = false
            myService = null
            Log.d("ocean-brush", "AIDL 连接已断开")
        } else {
            Log.d("ocean-brush", "AIDL未连接，无需解绑")
        }
    }

    fun sendHeartBeat(pkg: String): Boolean {
       return try {
            myService?.onHeartBeat(pkg)
            true
        } catch (e: RemoteException) {
            Log.e("AIDL链接异常", e.toString())
            false
        }
    }

    fun sendBrushMiss(): Boolean {
        return try {
            myService?.onBrushMiss()
            true
        } catch (e: RemoteException) {
            Log.e("AIDL链接异常", e.toString())
            false
        }
    }

    /**
     * 发送点击指令
     */
    fun sendClickAd(rate: Int, pkg: String): Boolean {
        return if (!isClicking) {
            isClicking = true
            try {
                Log.d("ocean-brush", "发送点击操作")
                myService?.clickAd(rate, pkg)
                true
            } catch (e: RemoteException) {
                Log.e("AIDL链接异常", e.toString())
                isClicking = false
                false
            }
        } else {
            Log.d("ocean-brush", "点击操作未完成，不能重复点击")
            false
        }
    }

    /**
     * 发送重启应用指令
     * 添加重置指令的防止多次点击只是为了规整划，不用在意！
     */
    fun sendResetApp(pkg: String): Boolean {
        return if (!isReset) {
            isReset = true
            try {
                myService?.resetApp(pkg)
                true
            } catch (e: RemoteException) {
                Log.e("AIDL链接异常", e.toString())
                isReset = false
                false
            }
        } else {
            Log.d("ocean-brush", "重启应用遭遇重复指令")
            false
        }
    }

    /**
     * 发送修改参数指令
     *
     * 只发送一次
     */
    fun sendChangeParameters(pkg: String): Boolean {
        return if (!isChangeComplete) {
            isChangeComplete = true
            try {
                myService?.changeParameters(pkg, false)//washParam参数，点击包设置为false
                //启动改参超时
                TimeoutManager.startTimeout(TimeoutTask.PARAM_CHANGE){
                    myService?.resetApp(pkg)
                }
                true
            } catch (e: RemoteException) {
                Log.e("AIDL链接异常", e.toString())
                isChangeComplete = false
                false
            }
        } else {
            Log.d("ocean-brush", "拦截成功！修改参数静止重复指令")
            false
        }
    }

    /**
     * 传入广告点击show数据
     */
    fun sendAdsChange(
        pkg: String,
        adLoadedCount: Int? = null,
        adShownCount: Int? = null,
        adClickCount: Int? = null
    ): Boolean {
        return try {
            //假设传入的int值为null，则默认为0
            myService?.adsChange(pkg, adLoadedCount ?: 0, adShownCount ?: 0, adClickCount ?: 0)
            true
        } catch (e: RemoteException) {
            Log.e("AIDL链接异常", e.toString())
            false
        }
    }

    fun sendReceiveResetOpenSuccessfully(): Boolean {
        return try {
            myService?.receiveResetOpenSuccessfully()
            true
        } catch (e: RemoteException) {
            Log.e("AIDL链接异常", e.toString())
            false
        }
    }


    /**
     * AIDL 回调，回调数据同步到 LiveData
     */
    private val callback = object : IMyAidlCallback.Stub() {

        override fun onClickComplete(b: Boolean) {
            Log.d("ocean-brush", "callback 收到回调：点击广告指令执行完毕")
            isClicking = false
            Handler(Looper.getMainLooper()).post {
                clickAdCompleteLiveData.value = b
            }
        }

        override fun onParametersComplete(b: Boolean) {
            Log.d("ocean-brush", "callback 收到回调：参数操作完成")
            isChangeComplete = false
            Handler(Looper.getMainLooper()).post {
                paramCompleteLiveData.value = b
            }
        }

        override fun onAdDisplayed() {

        }

        override fun onAdDisplayFailed() {

        }
    }

}
