package com.dafay.demo.aidl.proxy

import com.dafay.demo.aidl.callback.MethodCallback
import com.dafay.demo.aidl.inter.ReceiveListener
import com.dafay.demo.lib.base.utils.debug
import com.dafay.demo.lib.base.utils.error
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine


object TestServiceProxy : BaseServiceConnect() {

    private suspend fun checkConnectedService(): Boolean {
        val job = CoroutineScope(Dispatchers.Default).async {
            bindToService()
        }
        return job.await()
    }

    suspend fun bindService() {
        bindToService()
    }

    suspend fun add(value: Int): Int {
        if (!checkConnectedService()) {
            return -1
        }
        val job = CoroutineScope(Dispatchers.Default).async {
            doAdd(value)
        }
        try {
            return job.await()
        } catch (e: Exception) {
            error(e.message ?: "")
        }
        return -1
    }

    /**
     * 回调转同步
     */
    private suspend fun doAdd(value: Int): Int = withContext(Dispatchers.Default) {
        return@withContext suspendCoroutine { continuation ->
            remoteServiceProxy!!.add(value, object : MethodCallback.Stub() {
                override fun onSuccess(resultJson: String?) {
                    debug("add result:${resultJson}")
                    continuation.resume(resultJson?.toInt() ?: 0)
                }

                override fun onFailure(errorJson: String?) {
                    debug("add result:${errorJson}")
                    continuation.resumeWithException(RuntimeException("add fail"))
                }
            })
        }
    }

    suspend fun send(msg: String): Int {
        if (!checkConnectedService()) {
            return -1
        }
        return remoteServiceProxy!!.send(msg)
    }

    fun registerReceiverListener(listener: ReceiveListener?) {
        if (!receiveListeners.contains(listener)) {
            receiveListeners.add(listener)
        }
    }
}
