package com.seatel.mobilehall.ui.home.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.Request
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.adapter.MyCartAdapter
import com.seatel.mobilehall.ui.home.model.SeatelShopLocationModel
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.ErrorHandleView
import com.seatel.mobilehall.util.manager.OrderingManager
import com.seatel.mobilehall.util.view.OrderBottomBarView
import kotlinx.android.synthetic.main.activity_my_cart.*
import org.json.JSONObject


class MyCartActivity : BaseActivity(), View.OnClickListener, OrderBottomBarView.OnButtonClick,
    OrderingManager.OrderCallback {

    private var icDelete: MenuItem? = null
    private var cartAdapter: MyCartAdapter? = null

    override fun onCheckShipInsurance(isCheck: Boolean) {
    }

    override fun onCartModifyQty() {
        order_bottom_bar.setTotal(
            OrderingManager.getInstance().totalSelectedPrice,
            OrderingManager.getInstance().selectedCartsModels.size
        )
        cartAdapter?.notifyDataSetChanged()
    }

    override fun onDeliveryData(seatelShopLocationModel: SeatelShopLocationModel?) {
    }

    override fun onClick() {
        OrderActivity.launch(this)
    }

    override fun onCartModify() {
//        Log.d("data", Gson().toJson(OrderingManager.getInstance().cartsModels))
        order_bottom_bar.setTotal(
            OrderingManager.getInstance().totalSelectedPrice,
            OrderingManager.getInstance().selectedCartsModels.size
        )
        icDelete?.isVisible = OrderingManager.getInstance().selectedCartsModels.size > 0
    }

    override fun onClick(v: View?) {
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            Constant.CART_DEVICE_DETAIL -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    cartAdapter = MyCartAdapter(
                        this,
                        cart_error_view,
                        recycler_view_cart,
                        swipe_refresh_layout
                    )
                    recycler_view_cart.adapter = cartAdapter
//                    if (data.hasExtra(Constant.IntentKeys.IS_UPDATE_DEVICE)) {
//
//                    }
                }
            }
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_cart)
        OrderingManager.getInstance().orderCallback = this
        activityEnterUpAnimation()

        cart_error_view.errorMessage = getString(R.string.no_item_on_my_cart)
        order_bottom_bar.setOnButtonClick(this)

        recycler_view_cart.layoutManager = LinearLayoutManager(this)
        cartAdapter = MyCartAdapter(this, cart_error_view, recycler_view_cart, swipe_refresh_layout)
        recycler_view_cart.adapter = cartAdapter
    }

    fun getErrorView(): ErrorHandleView {
        return cart_error_view
    }

    override fun isDisplayHome(): Boolean {
        return true
    }

    override fun isShowBackButtonLeft(): Boolean {
        return true
    }

    override fun isCancelBackType(): Boolean {
        return true
    }

    override fun onDestroy() {
        super.onDestroy()
        OrderingManager.getInstance().clear()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        activityExitDownAnimation()

    }

    override fun onResume() {
        super.onResume()
        OrderingManager.getInstance().orderCallback = this
    }

    override fun onPause() {
        super.onPause()
        OrderingManager.getInstance().orderCallback = null
    }

    override fun getStringToolbarTitle(): String? {
        return getString(R.string.my_cart)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_my_cart, menu)
        icDelete = menu?.findItem(R.id.recycle_bin)
        icDelete?.isVisible = false
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.recycle_bin -> {
                deleteCart()
                true
            }
            else -> {
                super.onOptionsItemSelected(item)
            }
        }
    }

    fun getBottomBar(): OrderBottomBarView {
        return order_bottom_bar
    }

    companion object {
        fun launch(context: Context) {
            val intent = Intent(context, MyCartActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }

    private fun deleteCart() {
        SeatelAlertDialog.with(this, "Are you sure you want to delete?")
            .setPositiveButton("Yes") { _, _ ->
                object : SeatelJSONObjectRequest(this@MyCartActivity) {

                    override fun getFunctionName(): String {
                        return "carts/items"
                    }

                    override fun onGetUrlParams(requestParams: RequestParams?) {
                        requestParams?.put("phoneNumber", getPhoneLogin())
                        requestParams?.put("ids", OrderingManager.getInstance().selectedIds)
                        super.onGetUrlParams(requestParams)
                    }

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

                }.execute {
                    if ((it as JSONObject).optString("message") == "OK") {
                        cartAdapter = MyCartAdapter(
                            this,
                            cart_error_view,
                            recycler_view_cart,
                            swipe_refresh_layout
                        )
                        recycler_view_cart.adapter = cartAdapter
                    }
                }
            }.setNegativeButton("No") { dialog, _ -> dialog.dismiss() }.show()
    }
}
