package com.seatel.mobilehall.ui.base.presenter

import android.content.Context
import com.android.volley.Request
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.ui.base.interactor.RegisterPushTokenInteractor
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelUtils
import org.json.JSONException
import org.json.JSONObject

class RegisterPushTokenPresenter(
    private var mContext: Context,
    private var mPushToken: RegisterPushTokenInteractor.View
) : RegisterPushTokenInteractor.Presenter {

    override fun onRegisterPushToken(token: String, phoneNumber: String) {
        postPinVerifyRequest(token, phoneNumber).setOnErrorListener { error ->
            mPushToken.onRegisterPushTokenFailed(error)
        }.setOnResponseListener { response ->
            mPushToken.onRegisterPushTokenSucceed(response as JSONObject)
        }.execute()
    }

    private fun postPinVerifyRequest(
        token: String,
        phoneNumber: String
    ): SeatelJSONObjectRequest {

        return object : SeatelJSONObjectRequest(mContext) {

            override fun onGetBodyRequest(): String {
                val data = JSONObject()
                try {
                    data.put(
                        "deviceId",
                        SeatelUtils.getDeviceId(mContext)
                    )
                    data.put("token", token)
                    data.put("phoneNumber", phoneNumber)
                } catch (e: JSONException) {
                    e.printStackTrace()
                }

                return data.toString()
            }

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

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

        }
    }
}