package com.seatel.mobilehall.ui.home.presenter

import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.seatel.mobilehall.data.network.SeatelJSONArrayRequest
import com.seatel.mobilehall.ui.home.interactor.CategoryInteractor
import com.seatel.mobilehall.ui.home.model.CategoryModel
import com.seatel.mobilehall.util.Constant
import org.json.JSONArray

class CategoryPresenter(
    private var mContext: Context,
    private var categoryInteractor: CategoryInteractor.View
) : CategoryInteractor.Presenter {

    override fun onGetCategory(phoneNumber: String) {
        getCategoryRequest(phoneNumber).setOnErrorListener { error ->
            categoryInteractor.onGetCategoryFailed(error)
        }.setOnResponseListener { response ->
            categoryInteractor.onGetCategorySucceed(getCategoryModel(response as JSONArray))
        }.execute()
    }

    private fun getCategoryModel(response: JSONArray): ArrayList<CategoryModel> {
        val itemType = object : TypeToken<List<CategoryModel>>() {}.type
        return Gson().fromJson(response.toString(), itemType)

    }

    private fun getCategoryRequest(phoneNumber: String): SeatelJSONArrayRequest {
        return object : SeatelJSONArrayRequest(mContext) {

            override fun getFunctionName(): String {
                return if (phoneNumber.isNotBlank()) Constant.CATEGORY + "?phoneNumber=$phoneNumber" else
                    Constant.CATEGORY
            }
        }
    }
}