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

import android.content.Context
import com.seatel.mobilehall.data.network.SeatelJSONArrayRequest
import com.seatel.mobilehall.ui.home.interactor.AppProductsInteractor
import com.seatel.mobilehall.ui.home.model.AppProductsResponseModel
import com.seatel.mobilehall.util.Constant
import org.json.JSONArray

class AppProductsPresenter(
    private var mContext: Context,
    private var mInternetPlanView: AppProductsInteractor.View
) : AppProductsInteractor.Presenter {

    // private var mInternetPlanView: AppProductsInteractor.View = mContext as AppProductsInteractor.View
    private var mTypeQuery = ""

    fun setTypeQuery(query: String) {
        this.mTypeQuery = query
    }

    override fun onGetAppProducts(phone: String) {
        getGetInternetPlanRequest(phone).setOnErrorListener { error ->
            mInternetPlanView.onGetAppProductsFailed(error)
        }.setOnResponseListener { response ->
            mInternetPlanView.onGetAppProductsSucceed(getAppProductsModel(response as JSONArray))
        }.execute()
    }

    private fun getAppProductsModel(response: JSONArray): ArrayList<AppProductsResponseModel> {
        val internetPlanDataModels: ArrayList<AppProductsResponseModel> = ArrayList()

        for (i in 0 until response.length()) {
            val data = AppProductsResponseModel()
            data.code = response.optJSONObject(i).optString("code")
            data.id = response.optJSONObject(i).optString("id")
            data.name = response.optJSONObject(i).optString("name")
            data.icon = response.optJSONObject(i).optString("icon")
            data.subscriptionPlan = response.optJSONObject(i).optString("subscriptionPlan")
            data.canSubscribe = response.optJSONObject(i).optBoolean("canSubscribe")
            data.canChangePlan = response.optJSONObject(i).optBoolean("canChangePlan")
            data.type = response.optJSONObject(i).optString("type")

            internetPlanDataModels.add(data)
        }
        return internetPlanDataModels
    }

    private fun getGetInternetPlanRequest(phone: String): SeatelJSONArrayRequest {

        return object : SeatelJSONArrayRequest(mContext) {

            override fun getFunctionName(): String {
                return if (mTypeQuery.isEmpty() && phone.isNotEmpty()) Constant.APP_PRODUCTS + "?phoneNumber=$phone"
                else if (phone.isEmpty()) Constant.APP_PRODUCTS + "?status=active"
                else Constant.APP_PRODUCTS + "?phoneNumber=$phone&type=$mTypeQuery"
                /* return if (phone.isEmpty()) Constant.APP_PRODUCTS
                 else Constant.APP_PRODUCTS + "?phoneNumber=$phone"*/
            }
        }
    }
}