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

/**
 * 回调的方式
 */
object TestServiceProxy : BaseServiceConnect() {
    /**
     * 连接后执行
     */
    private fun connectedExec(onSuccess: () -> Unit, onFail: (Throwable) -> Unit) {
        bindToService(onSuccess) {
            onFail.invoke(RuntimeException("service connecte failure"))
        }
    }

    fun bindService(callback: FunCallback<Boolean>) {
        connectedExec({ callback.onSuccess(true) }, {
            callback.onFail(it)
        })
    }

    fun add(value: Int, callback: FunCallback<Int>) {
        connectedExec({
            funCachedThreadPool.submit {
                remoteServiceProxy!!.add(value, object : MethodCallback.Stub() {
                    override fun onSuccess(resultJson: String?) {
                        mainHandler.post {
                            debug("add result:${resultJson}")
                            callback.onSuccess(resultJson?.toInt() ?: 0)
                        }
                    }

                    override fun onFailure(errorJson: String?) {
                        mainHandler.post {
                            debug("add result:${errorJson}")
                            callback.onFail(RuntimeException(errorJson))
                        }
                    }
                })
            }
        }) {
            callback.onFail(it)
        }
    }

    fun send(msg: String, callback: FunCallback<Boolean>) {
        connectedExec({
            funCachedThreadPool.submit {
                val result = remoteServiceProxy!!.send(msg)
                mainHandler.post {
                    if (result == 0) {
                        callback.onSuccess(true)
                    } else {
                        callback.onFail(RuntimeException("send fail"))
                    }
                }
            }
        }) {
            callback.onFail(it)
        }
    }

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

    interface FunCallback<T> {
        fun onSuccess(t: T)
        fun onFail(e: Throwable)
    }
}
