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.TopPartnerInteractor
import com.seatel.mobilehall.ui.yes_member.model.PartnerCategoryModelItem
import com.seatel.mobilehall.ui.yes_member.model.TopPartnerModelItem
import org.json.JSONArray

class TopPartnerPresenter(
    private var mContext: Context, private var topPartnerInteractor: TopPartnerInteractor.View
) : TopPartnerInteractor.Presenter {


    override fun onTopPartnerData() {
        topPartnerRequest().setOnErrorListener { error ->
            topPartnerInteractor.responseTopPartnerFail(error)
        }.setOnResponseListener { response ->
            topPartnerInteractor.responseTopPartnerSucceed(getTopPartnerList(response as JSONArray))
        }.execute()
    }

    override fun onPartnerCategory() {
        partnerCategory().setOnErrorListener { error ->
            topPartnerInteractor.responsePartnerCategoryFail(error)
        }.setOnResponseListener { response ->
            topPartnerInteractor.responsePartnerCategorySucceed(getPartnerCategory(response as JSONArray))
        }.execute()
    }

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

    private fun topPartnerRequest(): SeatelJSONArrayRequest {
        return object : SeatelJSONArrayRequest(mContext) {
            override fun getFunctionName(): String {
                return "yes-member/top-partner"
            }

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

        }
    }


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

    private fun partnerCategory(): SeatelJSONArrayRequest {
        return object : SeatelJSONArrayRequest(mContext) {
            override fun getFunctionName(): String {
                return "yes-member/partner-category"
            }

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

        }
    }
}