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

class BuyDataPackFreedomPresenter(
    private var mContext: Context, private var mBuyDataView: BuyDataPackFreedomInteractor.View
) : BuyDataPackFreedomInteractor.Presenter {

    override fun onBuyData(
        phoneNumber: String,
        type: String,
        amount: Double,
        addon: Boolean,
        pricePlanCode: String,
        requestTime: String
    ) {
        postBuyDataRequest(
            phoneNumber, type, amount, addon, pricePlanCode, requestTime
        ).setOnErrorListener { error ->
            mBuyDataView.onBuyDataFailed(error)
        }.setOnResponseListener { _ ->
            mBuyDataView.onBuyDataSucceed()
        }.execute()
    }

    private fun postBuyDataRequest(
        phoneNumber: String,
        type: String,
        amount: Double,
        addon: Boolean,
        pricePlanCode: String,
        requestTime: String
    ): SeatelJSONObjectRequest {

        return object : SeatelJSONObjectRequest(mContext) {

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


            override fun onGetBodyRequest(): String {
                val data = JSONObject()
                try {
                    data.put("phoneNumber", phoneNumber)
                    data.put("type", type)
                    data.put("amount", amount)
                    if (addon) {
                        data.put("buyMore", "add-on")
                    }
                    data.put("pricePlanCode", pricePlanCode)
                    data.put("requestTime", requestTime)
                } catch (e: JSONException) {
                    e.printStackTrace()
                }

                return data.toString()
            }

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

        }
    }
}