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

class PartnerSearchPresenter(
    private var mContext: Context,
    private var partnerSearchInteractor: PartnerSearchInteractor.View
) : PartnerSearchInteractor.Presenter {


    override fun onTopPartner() {
        getTopPartnerRequest().setOnErrorListener { error ->
            partnerSearchInteractor.onTopPartnerFail(error)
        }.setOnResponseListener { response ->
            partnerSearchInteractor.onTopPartnerSucceed(getTopPartnerList(response as JSONArray))
        }.execute()
    }


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


    private fun getTopPartnerRequest(): SeatelJSONArrayRequest {


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

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

        }

    }

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


    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
            }

        }
    }


}