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

import android.content.Context
import com.android.volley.Request
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.ui.home.interactor.OnePlanDetailInteractor
import com.seatel.mobilehall.ui.home.model.OnePlanDetailModel
import com.seatel.mobilehall.ui.home.model.OnePlanDetailSecOneModel
import com.seatel.mobilehall.ui.home.model.OnePlanSecTwoModel
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.lang.LanguageManager
import org.json.JSONObject

class OnePlanDetailPresenter(private var mContext: Context) : OnePlanDetailInteractor.Presenter {

    private var mOnePlanView = mContext as OnePlanDetailInteractor.View
    private var lang: String? = "en"

    override fun onLoadData() {

        if (LanguageManager.getInstance(mContext).getLanguageCode() != null)
            lang = LanguageManager.getInstance(mContext).getLanguageCode()!!.toLowerCase()
        getOnePlanDetailRequest().setOnErrorListener { error ->
            mOnePlanView.onResponseFailed(error)
        }.setOnResponseListener { response ->
            mOnePlanView.onResponseSucceed(getOnePlanDetailModel(response as JSONObject))
        }.execute()
    }

    private fun getOnePlanDetailModel(response: JSONObject): OnePlanDetailModel {

        val onePlanDetailModel = OnePlanDetailModel()
        val onePlanSecOne = OnePlanDetailSecOneModel()
        onePlanSecOne.mobileImageUrl =
            response.optJSONObject("section1").optString("mobileImageUrl")

        onePlanDetailModel.onePlanDetailSecOneModel = onePlanSecOne
        val secTwo = OnePlanSecTwoModel()

        secTwo.title = response.optJSONObject("section2").optString("title")
        secTwo.subTitle = response.optJSONObject("section2").optString("subTitle")

        val featureList = response.optJSONObject("section2").optJSONArray("featureList")

        val features = ArrayList<String>()
        (0 until featureList.length()).mapTo(features) { featureList.optString(it) }

        secTwo.featureList = features
        onePlanDetailModel.onePlanSecTwoModel = secTwo

        onePlanDetailModel.setOneDescription(
            response.optJSONObject("section3").optString("description")
        )
        return onePlanDetailModel
    }

    private fun getOnePlanDetailRequest(): SeatelJSONObjectRequest {

        return object : SeatelJSONObjectRequest(mContext) {

            override fun getMethod(): Int {
                return Request.Method.GET
            }

            override fun getFunctionName(): String {
                return Constant.ONE_PLAN + "?lang=$lang"
            }

        }
    }
}