package com.lemonhc.mplus.framework.task

import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.android.core.Json
import com.github.kittinunf.fuel.android.extension.responseJson
import com.github.kittinunf.fuel.core.DataPart
import com.github.kittinunf.fuel.core.Method
import com.github.kittinunf.fuel.core.Request
import com.google.gson.Gson
import org.json.JSONObject

class ApiClient(val url: String, private val reqParams: List<Pair<String, Any?>>? = null, private val reqtFiles: List<DataPart>? = null, val header_param: Map<String, Any>? = null) {
    private var isProgressShow: Boolean = false
    private var encType: ENC_Type = ENC_Type.Default

    enum class ENC_Type{
        Default, Json, String
    }

    fun encType(type:ENC_Type): ApiClient {
        this.encType = type
        return this
    }

    fun isProgressShow(isShow: Boolean): ApiClient {
        this.isProgressShow = isShow
        return this
    }

    fun connect(callBackHandler: (JSONObject?) -> Unit) {
        val fuel: Request = reqtFiles?.let {
            var fuel: Request = Fuel.upload(url, Method.POST, reqParams)
            fuel.dataParts {_, _ -> it }
            return@let fuel
        } ?: Fuel.post(url, reqParams)

        run {
            var header: MutableMap<String, Any> = header_param?.toMutableMap() ?: return@run
            fuel.header(header)
        }

        when(encType) {
            ENC_Type.Json -> {
                run {
                    val param: List<Pair<String, Any?>> = reqParams ?: return@run
                    val json: String = Gson().toJson(param.toMap())
                    fuel.body(json)
                }
            }
        }

        fuel.responseJson{_, _, result ->
            val json: Json = result.component1() ?: return@responseJson
            callBackHandler(json.obj())
        }
    }

}
