package com.seatel.mobilehall.ui.login.presenter

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

class UnRegisterPushTokenPresenter(
    private var mContext: Context,
    private var mPushToken: UnRegisterPushTokenInteractor.View? = null
) : UnRegisterPushTokenInteractor.Presenter {
    private var unRegisterRequest: SeatelJSONObjectRequest? = null
    override fun onUnRegisterPushToken(phoneNumber: String) {
        postPinVerifyRequest(phoneNumber).setOnErrorListener { error ->
            mPushToken?.onUnRegisterPushTokenFailed(error)
        }.setOnResponseListener { response ->
            mPushToken?.onUnRegisterPushTokenSucceed(response as JSONObject)
        }.execute()
    }

    fun onDestroy() {
        mPushToken = null
    }

    private fun postPinVerifyRequest(phoneNumber: String): SeatelJSONObjectRequest {
        unRegisterRequest?.cancel()
        unRegisterRequest = object : SeatelJSONObjectRequest(mContext) {

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

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

                return data.toString()
            }

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

        }
        return unRegisterRequest!!
    }
}