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.FAQDetailInteractor
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 FAQDetailPresenter(var context: Context) : FAQDetailInteractor.Presenter {

    var view = context as FAQDetailInteractor.View

    override fun loadData(id: String) {
        getAnswer(id).setOnErrorListener { error ->
            view.responseFailedFAQDetail(error)
        }.setOnResponseListener { response ->
            view.responseSucceedFAQDetailData(getAnswerData(response as JSONObject))
            view.responseSucceedGetRelatedQuestion(getRelatedQustionList(response))
        }.execute()
    }

    private fun getRelatedQustionList(jsonObject: JSONObject): List<FAQModel> {
        val relatedQuestionList = ArrayList<FAQModel>()
        val data = jsonObject.getJSONArray("relatedFaqs")
        for (i in 0 until data.length()) {
            val question = FAQModel()
            question.question = data.getJSONObject(i).optString("question")
            question.id = data.getJSONObject(i).optString("_id")
            relatedQuestionList.add(question)
        }

        return relatedQuestionList
    }

    private fun getAnswerData(jsonObject: JSONObject): String {
        return jsonObject.optJSONArray("data").getJSONObject(0).optString("answer")
    }


    private fun getAnswer(id: String): SeatelJSONObjectRequest {
        return object : SeatelJSONObjectRequest(context) {

            override fun getFunctionName(): String {
                return Constant.ANSWER + id + "?lang=${SeatelUtils.getLangaugeCode(context)}&type=mobile"
            }

        }
    }
}