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.TopupTransactionInteractor
import com.seatel.mobilehall.util.Constant
import org.json.JSONException
import org.json.JSONObject

class TopupTransactionPresenter(private var mContext: Context,
private var mUnionPayView: TopupTransactionInteractor.View) :
    TopupTransactionInteractor.Presenter {


    override fun onTopup(
        phoneNumber: String,
        pin: String,
        orderId: String,
        type: String,
        status: String,
        paymentType: String,
        amount: Double
    ) {
        getSignUpRequest(
            phoneNumber,
            pin,
            orderId,
            type,
            status,
            paymentType,
            amount
        ).setOnErrorListener { error ->
            mUnionPayView.onTopupFailed(error)
        }.setOnResponseListener { response ->
            val data = response as JSONObject
            var remark = ""
            var amount: Double? = null
            if (data.has("remark"))
                remark = data.optString("remark", "")
            if (data.has("amount"))
                amount = data.optDouble("amount")
            mUnionPayView.onTopupSucceed(paymentType, remark, amount!!)
        }.execute()
    }

    private fun getSignUpRequest(
        phoneNumber: String,
        pin: String,
        orderId: String,
        type: String,
        status: String,
        paymentType: String,
        amount: Double
    ): SeatelJSONObjectRequest {

        return object : SeatelJSONObjectRequest(mContext) {

            override fun onGetBodyRequest(): String {
                val data = JSONObject()
                try {
                    data.put("phoneNumber", phoneNumber)
                    data.put("pin", pin)
                    data.put("orderId", orderId)
                    data.put("type", type)
                    data.put("status", status)
                    data.put("paymentType", paymentType)
                    data.put("amount", amount)
                } catch (e: JSONException) {
                    e.printStackTrace()
                }

                return data.toString()
            }

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


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


        }
    }
}