package com.yidian.common.services

import android.util.Log
import com.yidian.xarc.xbrid.XBridManager
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xarc.xevent.XEventManager
import com.yidian.xarc.xrouter.ResultResolver
import com.yidian.yac.core.zap.ZapService
import com.yidian.yac.core.zap.ZapTicket
import org.json.JSONObject

/**
 * @description: xevent支持类
 * @author: huyajun
 * @date:  2020/9/27
 **/

class XEventService : ZapService() {
    override fun onAction(
        path: String,
        action: String,
        params: Any,
        options: Any,
        resolver: ResultResolver
    ) {
        when (action) {
            "postEvent" -> {
                params as JSONObject
                val name: String = params["name"] as String
                val body = params["body"]
                XEventManager.post(XBaseEvent(name, body))
                //向flutter发送Event事件
                ZapTicket("flutter-event")
                    .withAction("handleEvent")
                    .withServiceParams(params)
                    .onLost { result ->
                        Log.d(TAG, "onLost: $result")
                    }
                    .onResult { result ->
                        Log.d(TAG, "flutter-event+onResult: $result")
                    }.ship()
                XBridManager.postEvent(name, body, null)
                resolver.success("事件已发送")
            }
        }
    }

    override fun onInit() {
    }

    override fun onExit() {
    }

    companion object {
        const val name: String = "xevent"
        private val TAG = "XEventService"
        fun postEvent(xbaseEvent: XBaseEvent) {
            val jsonObject = JSONObject()
            jsonObject.put("name", xbaseEvent.name)
            jsonObject.put("body", xbaseEvent.body)
            ZapTicket(name)
                .withAction("postEvent")
                .withServiceParams(jsonObject)
                .onLost { result ->
                    Log.d(TAG, "onLost: $result")
                }
                .onResult { result ->
                    Log.d(TAG, "onResult: $result")
                }.ship()
        }
    }

}