package com.seatel.mobilehall.ui.home.presenter

import android.content.Context
import android.text.TextUtils
import com.android.volley.Request
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.ui.home.interactor.MyOrderInteractor
import com.seatel.mobilehall.ui.home.model.DataPlansOrderModel
import com.seatel.mobilehall.ui.home.model.MyOrderItemModel
import com.seatel.mobilehall.ui.home.model.MyOrderListModel
import com.seatel.mobilehall.util.Constant
import org.json.JSONObject

class MyOrderPresenter(private var mContext: Context) : MyOrderInteractor.Presenter {

    private var mView = mContext as MyOrderInteractor.View

    //    private var typeOrder = "processing"
    private var searchStr = ""
    private var phoneNumber = ""
    private var isHistory = false

    fun setPhoneNumber(phoneNumber: String) {
        this.phoneNumber = phoneNumber
    }

    fun setsearchStr(searchStr: String) {
        this.searchStr = searchStr
    }

    fun setIsHistory(history: Boolean) {
        this.isHistory = history
    }

//    fun setTypeOrder(typeOrder: String) {
//        this.typeOrder = typeOrder
//    }

    override fun onGetMyOrderData(offset: Int) {
        getMyOrderRequest(offset).setOnErrorListener { error ->
            mView.responseMyOrderFail(error)
        }.setOnResponseListener { response ->
            mView.responseMyOrderSucceed(getMyOrderList(response as JSONObject))
        }.execute()
    }

    private fun getMyOrderList(response: JSONObject): ArrayList<MyOrderListModel> {
        val notificationListModel = ArrayList<MyOrderListModel>()
        var itemData = response.optJSONArray("data")
        var simIcon = response.optString("simIcon")
        var simPriceIcon = response.optString("simPriceIcon")
        var deviceIcon = response.optString("deviceIcon")
//        var scratchCardIcon = response.optString("scratchCardIcon")
        var topUpIcon = response.optString("topUpIcon")
        for (i in 0 until itemData.length()) {
            val data = MyOrderListModel()
            data.orderId = itemData.optJSONObject(i).optLong("orderId")
            data.orderDate = itemData.optJSONObject(i).optString("date")
            data.orderStatus = itemData.optJSONObject(i).optString("status")
            data.paymentMethod = itemData.optJSONObject(i).optString("paymentMethod", "")
            data.tranId = itemData.optJSONObject(i).optString("tranId", "")
            data.orderTotalPrice = itemData.optJSONObject(i).optDouble("totalPrice")
            data.orderTotalQuantity = itemData.optJSONObject(i).optInt("totalQuantity")
            data.orderTotalShipmentInsurace =
                itemData.optJSONObject(i).optDouble("shipmentInsurancePrice", 0.0)

            val itemsList = ArrayList<MyOrderItemModel>()
            val items = itemData.optJSONObject(i).optJSONArray("items")

            for (j in 0 until items.length()) {
                val dataItems = MyOrderItemModel()
                dataItems.typeItem = items.optJSONObject(j).optString("type")
                dataItems.quantity = items.optJSONObject(j).optInt("quantity")

                if (dataItems.typeItem == Constant.SIM_CARD) {
                    dataItems.itemIcon = simIcon
                    dataItems.simNumber = items.optJSONObject(j).optString("simCardNumber")
                    dataItems.simPrice = items.optJSONObject(j).optDouble("simCardPrice")
                    dataItems.totalPrice = items.optJSONObject(j).optDouble("totalPrice")
                    dataItems.topupAmount = items.optJSONObject(j).optDouble("topUpAmount")

                    val itemPlan = items.optJSONObject(j).optJSONObject("planSubscription")
                    if (itemPlan != null && !TextUtils.isEmpty(itemPlan.optString("planName"))) {
                        val itemPlanStore = ArrayList<DataPlansOrderModel>()

                        itemPlanStore.add(
                            DataPlansOrderModel(
                                mContext.getString(R.string.phone_number),
                                simIcon,
                                items.optJSONObject(j).optString("simCardNumber"),
                                items.optJSONObject(j).optDouble("simCardPrice")
                            )
                        )
                        itemPlanStore.add(
                            DataPlansOrderModel(
                                mContext.getString(R.string.sim_price),
                                simPriceIcon,
                                mContext.getString(R.string.sim_price),
                                items.optJSONObject(j).optDouble("cardPrice", 0.50)
                            )
                        )
                        itemPlanStore.add(
                            DataPlansOrderModel(
                                "Top Up",
                                topUpIcon,
                                "Top Up Amount",
                                items.optJSONObject(j).optDouble("topUpAmount")
                            )
                        )
                        itemPlanStore.add(
                            DataPlansOrderModel(
                                "Plan Subscription",
                                itemPlan.optString("planIcon"),
                                itemPlan.optString("planName"),
                                0.0
                            )
                        )

                        val addOnItem = itemPlan.optJSONArray("addOns")
                        if (addOnItem.length() > 0) {
                            for (l in 0 until addOnItem.length()) {
                                val planName = addOnItem.optJSONObject(l).optString("addOnName")
                                if (!TextUtils.isEmpty(planName)) {
                                    itemPlanStore.add(
                                        DataPlansOrderModel(
                                            "Add On",
                                            addOnItem.optJSONObject(l).optString("addOnIcon", ""),
                                            planName,
                                            addOnItem.optJSONObject(l).optDouble("amount", 0.0),
                                            true,
                                            addOnItem.optJSONObject(l).optInt("duration", 0)
                                        )
                                    )
                                }
                            }
                        }
                        dataItems.dataPlan = itemPlanStore
                    }
                } else if (dataItems.typeItem == Constant.DEVICE) {
                    if (items.optJSONObject(j).has("thumbnailUrl"))
                        dataItems.itemIcon = items.optJSONObject(j).optString("thumbnailUrl")
                    else dataItems.itemIcon = deviceIcon
                    dataItems.brand = items.optJSONObject(j).optString("brand")
                    dataItems.deviceUrl = items.optJSONObject(j).optString("deviceUrl")
                    dataItems.deviceName = items.optJSONObject(j).optString("deviceName")
                    dataItems.color = items.optJSONObject(j).optString("color")
                    dataItems.colorCode = items.optJSONObject(j).optString("colorCode", "")
                    dataItems.colorId = items.optJSONObject(j).optString("colorId", "")
                    dataItems.storage = items.optJSONObject(j).optInt("storage")
                    dataItems.totalPrice = items.optJSONObject(j).optDouble("totalPrice")
                    dataItems.unitPrice = items.optJSONObject(j).optDouble("unitPrice")

                } else if (dataItems.typeItem == Constant.SRATCH_CARD) {
                    dataItems.deviceName = mContext.getString(R.string.top_up_card)
                    dataItems.itemIcon = items.optJSONObject(j).optString("scratchCardIcon")
                    dataItems.scratchCardAmount =
                        items.optJSONObject(j).optDouble("scratchCardAmount")
                }
                itemsList.add(dataItems)
            }
            data.orderData = itemsList

            notificationListModel.add(data)
        }
        return notificationListModel

    }

    private fun getStrURL(): String {
        return if (isHistory) Constant.ORDERS_HISTORY else Constant.ORDERS
    }

    private fun getMyOrderRequest(offset: Int): SeatelJSONObjectRequest {

        return object : SeatelJSONObjectRequest(mContext) {


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

            override fun getFunctionName(): String {
                return "${getStrURL()}?limit=10&offset=$offset&phoneNumber=$phoneNumber&search=$searchStr"  //"?phoneNumber=$phoneNumber"
            }


        }
    }

}