package com.seatel.mobilehall.ui.yes_member.presenter

import android.content.Context
import com.android.volley.Request
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.seatel.mobilehall.data.network.SeatelJSONArrayRequest
import com.seatel.mobilehall.ui.yes_member.interactor.PartnerCategoryByNameInteractor
import com.seatel.mobilehall.ui.yes_member.model.PartnerByNameModel
import org.json.JSONArray

class PartnerCategoryByNamePresenter(
    private var mContext: Context,
    private var topPartnerInteractor: PartnerCategoryByNameInteractor.View
) : PartnerCategoryByNameInteractor.Presenter {


    override fun onPartnerCategoryByName(name: String) {
        partnerCategroyRequest(name).setOnErrorListener { error ->
            topPartnerInteractor.responsePartnerCategoryByNameFail(error)
        }.setOnResponseListener { response ->
            topPartnerInteractor.responsePartnerCategoryByNameSucceed(
                getPartnerCategoryByNameList(
                    response as JSONArray
                )
            )
        }.execute()
    }


    private fun getPartnerCategoryByNameList(response: JSONArray): ArrayList<PartnerByNameModel> {
        val gson = Gson()
        val responseString = response.toString()
        val listType = object : TypeToken<ArrayList<PartnerByNameModel>>() {}.type
        return gson.fromJson(responseString, listType)
    }

    private fun partnerCategroyRequest(name: String): SeatelJSONArrayRequest {
        return object : SeatelJSONArrayRequest(mContext) {
            override fun getFunctionName(): String {
                return "yes-member/partner?name=$name"
            }

            override fun getMethod(): Int {
                return Request.Method.GET
            }

        }
    }


}