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.SupportedDeviceInteractor
import com.seatel.mobilehall.ui.home.model.SupportedDeviceModel
import com.seatel.mobilehall.util.Constant
import org.json.JSONArray

class SupportedDevicePresenter(var mContext: Context) : SupportedDeviceInteractor.Presenter {


    var supportedDeviceView = mContext as SupportedDeviceInteractor.View

    override fun onLoadData() {
        getSupportedDeviceRequest().setOnErrorListener { error ->
            supportedDeviceView.responseFailed(error)

        }.setOnResponseListener { response ->
            supportedDeviceView.responseSucceedSupportedDeviceData(getSupportedDeviceModel(response as JSONArray))
        }.execute()
    }

    fun getSupportedDeviceModel(respone: JSONArray): ArrayList<SupportedDeviceModel> {

        val supportedDeviceMOdelList = ArrayList<SupportedDeviceModel>()

        for (i in 0 until respone.length()) {
            val supportedDeviceModel = SupportedDeviceModel()
            supportedDeviceModel.brand = respone.getJSONObject(i).optString("brand")


            val devices = ArrayList<SupportedDeviceModel.Devices>()
            val deviceRespone = respone.getJSONObject(i).optJSONArray("devices")


            for (k in 0 until deviceRespone.length()) {
                val device = SupportedDeviceModel.Devices()
                device._id = deviceRespone.getJSONObject(k).optString("_id")
                device.brand = deviceRespone.getJSONObject(k).optString("brand")
                device.name = deviceRespone.getJSONObject(k).optString("name")
                device.isArchived = deviceRespone.getJSONObject(k).optBoolean("isArchived")
                device.osVersion = deviceRespone.getJSONObject(k).optString("osVersion")
                devices.add(device)
            }

            supportedDeviceModel.devices = devices
            supportedDeviceMOdelList.add(supportedDeviceModel)
        }

        return supportedDeviceMOdelList
    }


    private fun getSupportedDeviceRequest(): SeatelJSONArrayRequest {
        return object : SeatelJSONArrayRequest(mContext) {

            override fun getFunctionName(): String {
                return Constant.SUPPORTED_DEVICE
            }


        }
    }
}