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

import android.content.Context
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.ui.home.interactor.FAQsInteractor
import com.seatel.mobilehall.ui.home.model.FAQModel
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelUtils
import org.json.JSONObject

class FAQsPresenter(var mContext: Context) : FAQsInteractor.Presenter {


    var faqsView = mContext as FAQsInteractor.View

    override fun onLoadData(search: String, offset: Int) {
        getFAQList(search, offset).setOnErrorListener { error ->
            faqsView.responseFailed(error)

        }.setOnResponseListener { response ->
            faqsView.responseSucceedFAQsData(
                getFAQData(response as JSONObject),
                getTotalCount(response)
            )
        }.execute()
    }

    private fun getTotalCount(response: JSONObject): Int {

        return response.optJSONObject("metadata").optInt("total")
    }

    private fun getFAQData(response: JSONObject): ArrayList<FAQModel> {

        val faqList = ArrayList<FAQModel>()
        val data = response.optJSONArray("data")
        for (i in 0 until data.length()) {
            val faqModel = FAQModel()
            faqModel.id = data.getJSONObject(i).optString("_id")
            faqModel.question = data.getJSONObject(i).optString("question")
            faqList.add(faqModel)
        }

        return faqList
    }

    private fun getFAQList(search: String, offset: Int): SeatelJSONObjectRequest {
        return object : SeatelJSONObjectRequest(mContext) {

            override fun getFunctionName(): String {
                return Constant.FAQs + "?lang=${SeatelUtils.getLangaugeCode(mContext)}&type=mobile&search=$search&offset=$offset"
            }

        }
    }
}