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

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.NoConnectionError
import com.android.volley.Request
import com.android.volley.TimeoutError
import com.android.volley.VolleyError
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.databinding.ActivityHistoryBinding
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.adapter.AdapterListParentOrder
import com.seatel.mobilehall.ui.home.interactor.MyOrderInteractor
import com.seatel.mobilehall.ui.home.model.MyOrderListModel
import com.seatel.mobilehall.ui.home.presenter.MyOrderPresenter
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.ErrorHandleView
import org.json.JSONObject

class HistoryActivity : BaseActivity<ActivityHistoryBinding>(), MyOrderInteractor.View {

    private var mMyOrderPresenter: MyOrderPresenter? = null
    private var mMyOrderAdapter: AdapterListParentOrder? = null
    private var mView: MyOrderInteractor.View? = null
    private var linearLayoutManager: LinearLayoutManager? = null
    private var mOffset = 0
    private val LIMIT_OFFSET = 10

    override fun getViewBinding(): ActivityHistoryBinding {
        return ActivityHistoryBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityEnterUpAnimation()
        //  setContentView(R.layout.activity_history)

        mView = this
        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
        mMyOrderPresenter = MyOrderPresenter(this)
        mMyOrderPresenter?.setPhoneNumber(getPhoneLogin())
        mMyOrderPresenter?.setIsHistory(true)
        getMyOrderList()
//        mMyOrderPresenter?.onGetMyOrderData(mOffset)

        mMyOrderAdapter = mView?.let { AdapterListParentOrder(this, ArrayList(), true, it) }
        binding.recyclerViewHistory.adapter = mMyOrderAdapter

        linearLayoutManager = LinearLayoutManager(this)
        binding.recyclerViewHistory.layoutManager = linearLayoutManager

        binding.recyclerViewHistory.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                mMyOrderAdapter?.onScrollEvent(linearLayoutManager!!)
            }
        })
    }

    private fun deleteOrderHistory(orderId: String) {
        SeatelAlertDialog.with(this, "Are you sure you want to delete?")
            .setPositiveButton("Yes") { dialog, _ ->
                object : SeatelJSONObjectRequest(this@HistoryActivity) {

                    override fun getFunctionName(): String {
                        return "orders/$orderId"
                    }

                    override fun getMethod(): Int {
                        return Request.Method.DELETE
                    }
                }.execute {
                    if ((it as JSONObject).optString("message") == "OK") {
                        getMyOrderList()
                    }
                }
                dialog.dismiss()
            }.setNegativeButton("No") { dialog, _ -> dialog.dismiss() }.show()
    }

    override fun onDeletedOrderId(orderId: String) {
        deleteOrderHistory(orderId)
    }

    private fun getMyOrderList() {
        mMyOrderAdapter?.clearData()
        mOffset = 0
        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
        mMyOrderPresenter?.onGetMyOrderData(mOffset)
    }

    override fun onClickConfirmOrder(orderId: String) {
    }

    override fun onLoadMore() {
        mOffset += LIMIT_OFFSET
        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
        mMyOrderPresenter?.onGetMyOrderData(mOffset)
    }

    override fun responseMyOrderSucceed(myOrderList: ArrayList<MyOrderListModel>) {
        if (myOrderList.isEmpty() && mOffset == 0) {
            binding.errorView.errorMessage = getString(R.string.no_myorder)
            binding.errorView.setViewMode(ErrorHandleView.Mode.NO_DATA)
        } else {
            mMyOrderAdapter?.addItems(myOrderList)
            binding.errorView.visibility = View.GONE
        }
    }

    override fun responseMyOrderFail(error: VolleyError) {
        when (error) {
            is TimeoutError -> {
                binding.errorView.errorMessage = getString(R.string.connection_timeout)
                binding.errorView.setViewMode(ErrorHandleView.Mode.TIME_OUT)
            }

            is NoConnectionError -> {
                binding.errorView.errorMessage = getString(R.string.message_no_internet)
                binding.errorView.setViewMode(ErrorHandleView.Mode.NO_INTERNET)
            }

            else -> {
                if (mOffset == 0) {
                    binding.errorView.errorMessage = getString(R.string.no_myorder)
                    binding.errorView.setViewMode(ErrorHandleView.Mode.NO_DATA)
                } else {
                    binding.errorView.visibility = View.GONE
                }
            }
        }
    }

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

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

    override fun isDisplayHome(): Boolean {
        return true
    }

    override fun isShowBackButtonLeft(): Boolean {
        return true
    }

    override fun isCancelBackType(): Boolean {
        return true
    }

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

}
