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.NotificationListInteractor
import com.seatel.mobilehall.ui.home.model.NotificationModel
import com.seatel.mobilehall.util.SeatelUtils
import org.json.JSONObject

class NotificationListPresenter(private var mContext: Context) :
    NotificationListInteractor.Presenter {

    private var mNotificationList = mContext as NotificationListInteractor.View

    override fun onLoadData(phoneNumber: String, offset: Int) {
        getNotificationListRequest(phoneNumber, offset).setOnErrorListener { error ->
            mNotificationList.responseFail(error)
        }.setOnResponseListener { response ->
            mNotificationList.responseSucceed(getNotificationList(response as JSONObject))
        }.execute()
    }

    private fun getNotificationList(response: JSONObject): ArrayList<NotificationModel> {
        val notificationListModel = ArrayList<NotificationModel>()
        val data = response.optJSONArray("data")
        for (i in 0 until data.length()) {
            val notificationModel = NotificationModel()
            notificationModel.title = data.optJSONObject(i).optString("title")
            notificationModel.message = data.optJSONObject(i).optString("message")
            notificationModel.createdAt = data.optJSONObject(i).optString("createdAt")
            notificationModel.hasSeen = data.optJSONObject(i).optBoolean("hasSeen")
            notificationModel.typeRow = data.optJSONObject(i).optString("type", "")
            notificationListModel.add(notificationModel)
        }
        return notificationListModel

    }

    private fun getNotificationListRequest(
        phoneNumber: String,
        offset: Int
    ): SeatelJSONObjectRequest {

        return object : SeatelJSONObjectRequest(mContext) {
            override fun getFunctionName(): String {
                return "v2/notifications?limit=10&offset=$offset&deviceId=${
                    SeatelUtils.getDeviceId(
                        mContext
                    )
                }&phoneNumber=$phoneNumber"
            }

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

}