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.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 kotlinx.android.synthetic.main.activity_history.*
import org.json.JSONObject

class HistoryActivity : BaseActivity(), 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 onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityEnterUpAnimation()
        setContentView(R.layout.activity_history)

        mView = this
        error_view.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) }
        recycler_view_history.adapter = mMyOrderAdapter

        linearLayoutManager = LinearLayoutManager(this)
        recycler_view_history.layoutManager = linearLayoutManager

        recycler_view_history.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
        error_view.setViewMode(ErrorHandleView.Mode.LOADING)
        mMyOrderPresenter?.onGetMyOrderData(mOffset)
    }

    override fun onClickConfirmOrder(orderId: String) {
    }

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

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

    override fun responseMyOrderFail(error: VolleyError) {
        when (error) {
            is TimeoutError -> {
                error_view.errorMessage = getString(R.string.connection_timeout)
                error_view.setViewMode(ErrorHandleView.Mode.TIME_OUT)
            }
            is NoConnectionError -> {
                error_view.errorMessage = getString(R.string.message_no_internet)
                error_view.setViewMode(ErrorHandleView.Mode.NO_INTERNET)
            }
            else -> {
                if (mOffset == 0) {
                    error_view.errorMessage = getString(R.string.no_myorder)
                    error_view.setViewMode(ErrorHandleView.Mode.NO_DATA)
                } else {
                    error_view.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)
        }
    }

}
