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

import android.content.Context
import com.android.volley.Response
import com.android.volley.VolleyError
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.seatel.mobilehall.data.network.SeatelJSONArrayRequest
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.ui.home.interactor.BuyYesSimCardInteractor
import com.seatel.mobilehall.ui.home.model.CartRequestModel
import com.seatel.mobilehall.ui.home.model.PlanSubscriptionModel
import com.seatel.mobilehall.ui.home.model.YesNumberApiData
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.manager.CartManager
import org.json.JSONObject

/**
 *
 *
 * @author Noel
 * @version
 * @created on 18-Oct-18
 */
class BuyYesSimCardPresenter(private var view: BuyYesSimCardInteractor.View?) :
    BuyYesSimCardInteractor.OnFinishedListener {

    private var mGson = Gson()
    private var type = object : TypeToken<List<PlanSubscriptionModel>>() {
    }.type
    private var searchNumberRequest: SeatelJSONObjectRequest? = null
    private var planSubscriptionRequest: SeatelJSONArrayRequest? = null

    fun onGetPlanSubscription(context: Context) {
        planSubscriptionRequest?.cancel()
        planSubscriptionRequest = object : SeatelJSONArrayRequest(context) {

            override fun getFunctionName(): String {
                return Constant.SUBSCRIPTION_PLANS
            }

        }
        planSubscriptionRequest?.setOnErrorListener { error ->
            this@BuyYesSimCardPresenter.onGetPlanSubscriptionFailed(
                error
            )
        }
        planSubscriptionRequest?.setOnResponseListener { response ->
            try {
                val planSubscriptionModels: List<PlanSubscriptionModel> =
                    mGson.fromJson(response.toString(), type)
                this@BuyYesSimCardPresenter.onGetPlanSubscriptionSuccess(planSubscriptionModels)
            } catch (ex: Exception) {
                ex.printStackTrace()
                this@BuyYesSimCardPresenter.onGetPlanSubscriptionSuccess(null)
            }

        }
        planSubscriptionRequest?.execute()
        view?.showWaiting()
    }

    fun onSearchPhoneNumber(
        context: Context,
        search: String,
        postFix: Boolean = false,
        startPrice: Int? = null,
        endPrice: Int? = null,
        limit: Int,
        offset: Int = 0
    ) {
        searchNumberRequest?.cancel()
        searchNumberRequest = object : SeatelJSONObjectRequest(context) {

            override fun getFunctionName(): String {
                return getSearchNumberFunctionName(
                    context,
                    search,
                    postFix,
                    startPrice,
                    endPrice,
                    limit,
                    offset
                )
            }


        }
        searchNumberRequest?.setOnErrorListener { error ->
            this@BuyYesSimCardPresenter.onSearchPhoneNumberFailed(
                error
            )
        }
        searchNumberRequest?.setOnResponseListener { response ->
            try {
                val phoneNumbers: YesNumberApiData =
                    mGson.fromJson(response.toString(), YesNumberApiData::class.java)
                if (offset > 0) {
                    this@BuyYesSimCardPresenter.onSearchMorePhoneNumberSuccess(phoneNumbers)
                } else {
                    this@BuyYesSimCardPresenter.onSearchPhoneNumberSuccess(phoneNumbers)
                }
            } catch (ex: Exception) {
                ex.printStackTrace()
                if (offset > 0) {
                    this@BuyYesSimCardPresenter.onSearchMorePhoneNumberSuccess(null)
                } else {
                    this@BuyYesSimCardPresenter.onSearchPhoneNumberSuccess(null)
                }
            }

        }
        searchNumberRequest?.execute()
        if (offset == 0) {
            view?.showWaiting()
        }
    }

    private fun getSearchNumberFunctionName(
        context: Context,
        search: String,
        postFix: Boolean = false,
        startPrice: Int? = null,
        endPrice: Int? = null,
        limit: Int,
        offset: Int = 0
    ): String {
        val phoneNumber = SeatelSharePreferences.getInstance(context)?.getPhoneLogin()
        val queryStartPrice =
            if (startPrice != null) "&${Constant.START_PRICE}=$startPrice" else ""
        val queryEndPrice = if (startPrice != null) "&${Constant.END_PRICE}=$endPrice" else ""
        return Constant.SEARCH_PHONE_NUMBERS + "?${Constant.LIMIT}=$limit&${Constant.OFFSET}=$offset&${Constant.SEARCH}=$search&${Constant.POSTFIX}=$postFix$queryStartPrice$queryEndPrice&${Constant.PHONE_NUMBER}=$phoneNumber"
    }

    fun cancelSearchPhoneNumber() {
        view?.hideWaiting()
        searchNumberRequest?.cancel()
    }

    fun addSimCardToCard(context: Context, data: CartRequestModel<CartRequestModel.SimCard>) {
        val request = CartManager.addSimCardToCard(
            context,
            data,
            Response.ErrorListener { this.onAddSimToCardFailed(it) },
            Response.Listener { this.onAddSimToCardSuccess(it) })
        view?.showWaiting()
        request.execute()
    }

    fun onDestroy() {
        view = null
    }

    override fun onGetPlanSubscriptionFailed(throwable: VolleyError) {
        view?.apply {
            hideWaiting()
            showGetPlanSubscriptionFailed(throwable)
        }
    }

    override fun onGetPlanSubscriptionSuccess(data: List<PlanSubscriptionModel>?) {
        view?.apply {
            hideWaiting()
            showGetPlanSubscriptionSuccess(data)
        }
    }

    override fun onSearchPhoneNumberFailed(throwable: VolleyError) {
        view?.apply {
            hideWaiting()
            showSearchPhoneNumberFailed(throwable)
        }
    }

    override fun onSearchPhoneNumberSuccess(data: YesNumberApiData?) {
        view?.apply {
            hideWaiting()
            showSearchPhoneNumberSuccess(data)
        }
    }

    override fun onSearchMorePhoneNumberFailed(throwable: VolleyError) {
        view?.apply {
            hideWaiting()
            showSearchMorePhoneNumberFailed(throwable)
        }
    }

    override fun onSearchMorePhoneNumberSuccess(data: YesNumberApiData?) {
        view?.apply {
            hideWaiting()
            showSearchMorePhoneNumberSuccess(data)
        }
    }

    override fun onAddSimToCardFailed(throwable: VolleyError) {
        view?.apply {
            hideWaiting()
            showAddSimToCardFailed(throwable)
        }
    }

    override fun onAddSimToCardSuccess(data: JSONObject?) {
        view?.apply {
            hideWaiting()
            showAddSimToCardSuccess(data)
        }
    }
}
