package com.adealink.weparty.webview.jsbridge.data

import androidx.annotation.IntDef
import org.json.JSONObject

data class JSRequest(
    @RequestType val type: Int = TYPE_UNKNOWN,
    val methodName: String = "",
    val callbackId: String = "",
    var data: String? = null,
) {

    companion object {

        private const val KET_CALLBACK_ID = "callback_id"
        private const val KET_METHOD = "method"
        private const val KET_TYPE = "type"
        private const val KET_DATA = "data"

        const val TYPE_UNKNOWN = 0
        const val TYPE_INVOKE_METHOD = 1
        const val TYPE_ADD_LISTENER = 2
        const val TYPE_REMOVE_LISTENER = 3

        @IntDef(TYPE_UNKNOWN, TYPE_INVOKE_METHOD, TYPE_ADD_LISTENER, TYPE_REMOVE_LISTENER)
        internal annotation class RequestType

        fun parseJson(json: String?): JSRequest {
            if (json.isNullOrEmpty()) {
                return JSRequest(TYPE_UNKNOWN, "", "", null)
            }

            return try {
                val jsonObject = JSONObject(json)
                val requestType = jsonObject.optInt(KET_TYPE, TYPE_UNKNOWN)
                val methodName = jsonObject.optString(KET_METHOD, "")
                val callbackId = jsonObject.optString(KET_CALLBACK_ID, "")
                val dataJSONObject = jsonObject.optJSONObject(KET_DATA)
                JSRequest(requestType, methodName, callbackId, dataJSONObject?.toString())
            } catch (e: Exception) {
                JSRequest(TYPE_UNKNOWN, "", "", null)
            }
        }
    }


}