package com.seatel.mobilehall.util.manager

import android.content.Context
import com.android.volley.Request
import com.android.volley.Response
import com.google.gson.Gson
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.ui.application.MyApplication
import com.seatel.mobilehall.ui.home.model.CartRequestModel
import com.seatel.mobilehall.util.Constant
import org.json.JSONObject

/**
 *
 *
 * @author Noel
 * @version
 * @created on 19-Oct-18
 */
object CartManager {
    private val mGson = Gson()

    private fun <T : CartRequestModel.Item> addItemToCard(
        context: Context,
        data: CartRequestModel<T>,
        onErrorListener: Response.ErrorListener,
        onResponse: Response.Listener<JSONObject>
    ): SeatelJSONObjectRequest {
        val request = object : SeatelJSONObjectRequest(context) {

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

            override fun onGetBodyRequest(): String {
                return mGson.toJson(data)
            }

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


        }
        request.setOnErrorListener(onErrorListener)
        //   request.onErrorListener = onErrorListener
//        request.onResponseListener = onResponse
        request.setOnResponseListener {
            val dataReq = it as JSONObject
            if (dataReq.has("totalItem"))
                MyApplication.badgeCartCount = dataReq.optInt("totalItem")
            onResponse.onResponse(dataReq)
        }
        return request
    }

    fun addSimCardToCard(
        context: Context,
        card: CartRequestModel<CartRequestModel.SimCard>,
        onErrorListener: Response.ErrorListener,
        onResponse: Response.Listener<JSONObject>
    ): SeatelJSONObjectRequest {
        return addItemToCard(context, card, onErrorListener, onResponse)
    }

    fun addDeviceToCard(
        context: Context,
        card: CartRequestModel<CartRequestModel.Device>,
        onErrorListener: Response.ErrorListener,
        onResponse: Response.Listener<JSONObject>
    ): SeatelJSONObjectRequest {
        return addItemToCard(context, card, onErrorListener, onResponse)
    }

    fun addScratchToCard(
        context: Context,
        card: CartRequestModel<CartRequestModel.Scratch>,
        onErrorListener: Response.ErrorListener,
        onResponse: Response.Listener<JSONObject>
    ): SeatelJSONObjectRequest {
        return addItemToCard(context, card, onErrorListener, onResponse)
    }
}