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

class BannersPresenter(
    private var mContext: Context,
    private var mBannerView: BannersInteractor.View
) : BannersInteractor.Presenter {

    override fun onGetBanners() {
        getBannersRequest().setOnErrorListener { error ->
            mBannerView.onGetBannersFailed(error)
        }.setOnResponseListener { response ->
            mBannerView.onGetBannersSucceed(getBannersModel(response as JSONArray))
        }.execute()
    }

    private fun getBannersModel(response: JSONArray): ArrayList<BannersModel> {
        val bannersModel: ArrayList<BannersModel> = ArrayList()
        for (i in 0 until response.length()) {
            val bannersDataModel = BannersModel()
            bannersDataModel.setMobileUrl(response.getJSONObject(i).optString("imageUrl"))
            bannersDataModel.setUrl(response.getJSONObject(i).optString("url"))
            bannersDataModel.setType(response.getJSONObject(i).optString("type"))
            bannersDataModel.setTitle(response.getJSONObject(i).optString("title"))
            bannersModel.add(bannersDataModel)
        }
        return bannersModel
    }


    private fun getBannersRequest(): SeatelJSONArrayRequest {


        return object : SeatelJSONArrayRequest(mContext) {

            override fun getFunctionName(): String {
                return "app-promotions/banners?lang=${SeatelUtils.getLangaugeCode(mContext)}"
            }

        }
    }

}




