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 bannersList = ArrayList<BannersModel>()
        for (i in 0 until response.length()) {
            val obj = response.getJSONObject(i)
            val model = BannersModel().apply {
                url = obj.optString("url")
                imageUrl = obj.optString("imageUrl")
                type = obj.optString("type")
                title = obj.optString("title")
                actionType = obj.optString("actionType") // if exists
            }
            bannersList.add(model)
        }
        return bannersList
    }


    private fun getBannersRequest(): SeatelJSONArrayRequest {


        return object : SeatelJSONArrayRequest(mContext) {

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

        }
    }

}




