package com.adealink.weparty.stat

import com.adealink.frame.log.Log
import com.adealink.frame.statistics.BaseStatEvent
import com.adealink.frame.statistics.CommonEventValue
import com.adealink.frame.statistics.IEventValue
import com.adealink.frame.statistics.TAG_STAT
import com.adealink.weparty.App
import com.adealink.weparty.stat.data.ReportEventReq
import com.adealink.weparty.stat.datasource.remote.EventHttpService
import kotlinx.coroutines.launch

open class HttpEvent(override val eventId: String) : BaseStatEvent(eventId) {

    private val eventHttpService by lazy {
        App.instance.networkService.getHttpService(EventHttpService::class.java)
    }

    override val action: IEventValue = CommonEventValue.Action.EMPTY

    val scene = Param("scene")
    val targetUid = Param("targetUserNo")
    val businessId = Param("businessId")
    val extra = Param("extra")

    override fun send() {
        launch {
            Log.d(TAG_STAT, "report http event($eventId), scene:${scene.value}")
            val scene = scene.value as? String ?: return@launch
            val targetUid = targetUid.value as? String
            val businessId = businessId.value as? String

            eventHttpService.reportEvent(
                ReportEventReq(
                    eventId = eventId,
                    scene = scene,

                    targetUid = targetUid,
                    businessId = businessId,
                    extra = getExtraParams()
                )
            )
        }
    }

    private fun getExtraParams(): Map<String, String> {
        val extraMap = mutableMapOf<String, String>()

        val commonEvent = createEventMap()
        for (entry in commonEvent.entries) {
            extraMap[entry.key] = extra.value.toString()
        }

        val extra = extra.value as? Map<String, String>
        if (!extra.isNullOrEmpty()) {
            for (entry in extra.entries) {
                extraMap[entry.key] = entry.value
            }
        }
        return extraMap
    }

}