package com.yidian.common.services.http

import com.google.gson.Gson
import com.yidian.common.BuildConfig
import com.yidian.common.http.HttpResult
import com.yidian.common.services.http.callback.IMBRequestCallBack
import com.yidian.xarc.xrouter.ResultResolver
import com.yidian.yac.core.zap.ZapService
import org.json.JSONObject


/**
 * 网络请求服务类
 */
class MBHttpReqService : ZapService() {

  companion object {
    const val SERVICE_NAME: String = "NAHttpReq"
  }

  private lateinit var resolver: ResultResolver

  override fun onAction(path: String, action: String, params: Any, options: Any, resolver: ResultResolver) {
    this.resolver = resolver
    try {
      //params
      val realParams = params as JSONObject
      val apiPath = realParams.optString("path")
      val requestParams = realParams.optJSONObject("params")

      //options
      val requestOptions = options as JSONObject
      val method = requestOptions.optString("method", "POST")
      val host = requestOptions.optString("host", BuildConfig.API_URL)
      val url = host + apiPath
      val paramsMap: HashMap<String, String?> = parseParams(requestParams)

      //发起请求
      when (method) {
        "GET", "get" -> {
          MBRemoteDataSource.launchGetRequest(iMBRequestCallBackImpl, paramsMap, url)
        }
        "POST", "post" -> {
          MBRemoteDataSource.launchPostRequest(iMBRequestCallBackImpl, paramsMap, url)
        }
        else -> {
          resolver.fail(-1000, "request error", "不支持的请求方式")
        }
      }
    } catch (e: Exception) {
      e.printStackTrace()
      resolver.fail(-1001, "other error", "其他错误")
    }
  }

  override fun onExit() {
  }

  override fun onInit() {
  }

  private fun parseParams(requestParams: JSONObject?): HashMap<String, String?> {
    var hashMap: HashMap<String, String?> = HashMap()
    if (requestParams != null) {
      hashMap = HashMap()
      var key: String?
      val iterator = requestParams.keys()
      while (iterator.hasNext()) {
        key = iterator.next()
        hashMap[key] = requestParams.optString(key)
      }
    }
    return hashMap
  }

  private val iMBRequestCallBackImpl = object : IMBRequestCallBack {

    override fun getRequestSuccess(response: Any?) {
      val params = Gson().toJson(response)
      resolver.success(JSONObject(params))
    }

    override fun getRequestFailure(response: HttpResult<Any?>?) {
      response?.let {
        resolver.fail(response.code, null, response.reason)
      }
    }
  }


}
