package com.adealink.weparty.webview.stat

import com.adealink.frame.statistics.BaseStatEvent
import com.adealink.frame.statistics.CommonEventKey
import com.adealink.frame.statistics.IEventValue
import com.adealink.frame.statistics.StatClientError
import org.json.JSONObject

class WebViewStatEvent(override val action: IEventValue) : BaseStatEvent("web_view") {

    enum class Action(override val value: String, override val desc: String) : IEventValue {
        ERROR("error", "发生错误"),
        CLEAR_CACHE("clear_cache", "清理缓存"),
        LOAD("load", "加载"),
    }

    enum class Redirect(override val value: String, override val desc: String) : IEventValue {
        FALSE("0", "不是重定向"),
        TRUE("1", "是重定向"),
    }

    enum class Cache(override val value: String, override val desc: String) : IEventValue {
        NO_CACHE("0", "未用缓存"),
        DIRECT_CACHE("1", "直接使用本地缓存"),
        REDIRECT_CACHE("2", "重定向本地缓存"),
    }

    val page = Param(CommonEventKey.PAGE)
    val uri = Param(CommonEventKey.URI)
    val code = Param(CommonEventKey.CODE)
    val error = Param(CommonEventKey.ERROR)
    val result = Param(CommonEventKey.RESULT)
    val lastVersion = Param(CommonEventKey.LAST_VERSION)
    val newVersion = Param(CommonEventKey.NEW_VERSION)
    val type = Param(CommonEventKey.TYPE)
    val method = Param(CommonEventKey.METHOD)
    val cache = Param(CommonEventKey.CACHE)
    val redirect = Param(CommonEventKey.REDIRECT)
    val duration = Param(CommonEventKey.DURATION)
    var protocol = Param(CommonEventKey.PROTOCOL)
    val host = Param(CommonEventKey.HOST)
    var ua = Param(CommonEventKey.UA)

    override fun clientErrorInfo(): StatClientError? {
        if (action != Action.ERROR) {
            return null
        }
        val uri = uri.value?.toString() ?: return null
        val host = host.value?.toString() ?: ""
        val jsonObj = JSONObject()
        jsonObj.put("code", code.value)
        jsonObj.put("error", error.value)
        return StatClientError(host + uri, jsonObj.toString())
    }
}