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.PromotionsInteractor
import com.seatel.mobilehall.ui.home.model.PromotionListModel
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelUtils
import org.json.JSONArray

class PromotionsPresenter(private var mContext: Context) : PromotionsInteractor.Presenter {

    private var mPromotionView: PromotionsInteractor.View? = null
    private var requestPromotion: SeatelJSONArrayRequest? = null

    init {
        if (mContext != null)
            mPromotionView = mContext as PromotionsInteractor.View
    }

    fun onDestroy() {
        mPromotionView = null
    }

    override fun onGetPromotion(phone: String) {
        getGetPromotionRequest(phone).setOnErrorListener { error ->
            mPromotionView?.onGetPromotionFailed(error)
        }.setOnResponseListener { response ->
            mPromotionView?.onGetPromotionSucceed(getDataPromtionModel(response as JSONArray))
        }.execute()
    }

    private fun getDataPromtionModel(response: JSONArray): ArrayList<PromotionListModel> {
        val promotionDataModels: ArrayList<PromotionListModel> = ArrayList()
        for (i in 0 until response.length()) {
            val promotionModel = PromotionListModel()
            promotionModel.setIdPromotion(response.getJSONObject(i).optString("_id"))
            promotionModel.setBanner(response.getJSONObject(i).optString("imageUrl"))
            promotionModel.setPromotionType(response.getJSONObject(i).optString("type"))
            promotionModel.setUrl(response.getJSONObject(i).optString("url", ""))
            promotionDataModels.add(promotionModel)
        }
        return promotionDataModels
    }

    private fun getGetPromotionRequest(phone: String): SeatelJSONArrayRequest {
        requestPromotion?.cancel()
        requestPromotion = object : SeatelJSONArrayRequest(mContext) {

            override fun getFunctionName(): String {
                return Constant.PROMOTION + "?lang=${SeatelUtils.getLangaugeCode(mContext)}&phoneNumber=$phone"
            }

        }
        return requestPromotion!!
    }
}