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

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.NoConnectionError
import com.android.volley.TimeoutError
import com.android.volley.VolleyError
import com.seatel.mobilehall.R
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.interactor.UpdatedMyOrderProcessInteractor
import com.seatel.mobilehall.ui.home.model.MyOrderListModel
import com.seatel.mobilehall.ui.home.presenter.MyOrderPresenter
import com.seatel.mobilehall.ui.home.presenter.UpdatedMyOrderProcessPresenter
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.ErrorHandleView
import kotlinx.android.synthetic.main.activity_my_order.*
import org.json.JSONObject

class MyOrderActivity : BaseActivity(), View.OnClickListener, MyOrderInteractor.View,
    UpdatedMyOrderProcessInteractor.View {

    private var mMyOrderPresenter: MyOrderPresenter? = null
    private var mMyOrderAdapter: AdapterListParentOrder? = null
    private var mView: MyOrderInteractor.View? = null
    private var mPostOrder: UpdatedMyOrderProcessPresenter? = null
    private var linearLayoutManager: LinearLayoutManager? = null
    private var mOffset = 0
    private val mLimit = 10
    private var marginLayoutParams: ViewGroup.MarginLayoutParams? = null
    private var flagMove = 1
    private var lastSearchStr = ""

    override fun onClick(v: View?) {
        if (v != null) {
            when (v.id) {
                R.id.recycler_view_order_parent, R.id.error_view -> {
                    text_view_search_order.clearFocus()
                    SeatelUtils.hideKeyboard(this@MyOrderActivity)
                }
                else -> HistoryActivity.lunch(applicationContext)
            }
        }

    }

    override fun onDeletedOrderId(orderId: String) {
    }

    override fun onClickConfirmOrder(orderId: String) {
        SeatelAlertDialog.with(this, getString(R.string.you_have_recieved_this_order))
            .setCancelable(true).setPositiveButton("Yes") { dialog, _ ->
                error_view.setViewMode(ErrorHandleView.Mode.LOADING)
                mPostOrder?.onPutOrderProcess(orderId)
                dialog.dismiss()
            }.setNegativeButton("No") { dialog, _ -> dialog.dismiss() }.show()
    }

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

    override fun onLoadMore() {
        if (mMyOrderAdapter?.getSizeItems() == 0) return
        mOffset += mLimit
        error_view.setViewMode(ErrorHandleView.Mode.LOADING)
        mMyOrderPresenter?.onGetMyOrderData(mOffset)
    }

    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 -> {
                animateSearchBoxHideShow(true)
                error_view.errorMessage = getString(R.string.no_myorder)
                error_view.setViewMode(ErrorHandleView.Mode.NO_DATA)

            }
        }
    }

    private fun getMyOrderList() {
        text_view_search_order.clearFocus()
        SeatelUtils.hideKeyboard(this)
        mMyOrderAdapter?.clearData()
        mOffset = 0
        error_view.setViewMode(ErrorHandleView.Mode.LOADING)
        mMyOrderPresenter?.onGetMyOrderData(mOffset)
    }

    override fun onPostOrderProcessSucceed(response: JSONObject) {
        SeatelAlertDialog.with(this, getString(R.string.thank_you_for_purchase)).show()
        getMyOrderList()
    }

    override fun onPostOrderProcessTokenFailed(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
                }
            }
        }
    }

    private fun animateSearchBoxHideShow(isShow: Boolean) {
        if (isShow) {
            if (flagMove == 1) return
            flagMove = 1
            text_view_search_order.animate().translationY(0f).withEndAction {
                marginLayoutParams?.bottomMargin = 0
                recycler_view_order_parent.layoutParams = marginLayoutParams
            }.duration = 400
            recycler_view_order_parent.animate().translationY(0f).duration = 400

        } else {
            if (flagMove == 0) return
            flagMove = 0
            text_view_search_order.animate().translationY(-140f).duration = 400
            recycler_view_order_parent.animate().translationY(-140f).duration = 400
            marginLayoutParams?.bottomMargin = -140
            recycler_view_order_parent.layoutParams = marginLayoutParams
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityEnterUpAnimation()
        setContentView(R.layout.activity_my_order)
        text_view_search_order.hint = text_view_search_order.hint

        mView = this
        mPostOrder = UpdatedMyOrderProcessPresenter(this, this)

        error_view.setViewMode(ErrorHandleView.Mode.LOADING)
        mMyOrderPresenter = MyOrderPresenter(this)
        mMyOrderPresenter?.setPhoneNumber(getPhoneLogin())
        getMyOrderList()

        mMyOrderAdapter = mView?.let { AdapterListParentOrder(this, ArrayList(), false, it) }
        recycler_view_order_parent.adapter = mMyOrderAdapter
        linearLayoutManager = LinearLayoutManager(this)
        recycler_view_order_parent.layoutManager = linearLayoutManager

        marginLayoutParams = recycler_view_order_parent.layoutParams as ViewGroup.MarginLayoutParams

        recycler_view_order_parent.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                mMyOrderAdapter?.onScrollEvent(linearLayoutManager!!)
                if (dy > 0)
                    animateSearchBoxHideShow(false)
                else animateSearchBoxHideShow(true)
            }
        })

        text_view_bottom_eshop.text = getString(R.string.history)
        layout_call_view_my_order.setOnClickListener(this)

        recycler_view_order_parent.setOnClickListener(this)
//        error_view.setOnClickListener(this)

        text_view_search_order.setImeActionLabel("Search", EditorInfo.IME_ACTION_SEARCH)
        text_view_search_order.setOnEditorActionListener { _, actionId, _ ->
            when (actionId) {
                EditorInfo.IME_ACTION_SEARCH, EditorInfo.IME_ACTION_DONE -> {
                    if (!TextUtils.isEmpty(text_view_search_order.text.toString())) {
                        lastSearchStr = text_view_search_order.text.toString()
                        mMyOrderPresenter?.setsearchStr(lastSearchStr)
                        getMyOrderList()
                        return@setOnEditorActionListener true
                    } else if (TextUtils.isEmpty(text_view_search_order.text.toString()) && lastSearchStr.isNotEmpty()) {
                        mMyOrderPresenter?.setsearchStr("")
                        getMyOrderList()
                    } else {
                        text_view_search_order.clearFocus()
                        SeatelUtils.hideKeyboard(this)
                    }
                }
            }
            return@setOnEditorActionListener false
        }

    }

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

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

    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, MyOrderActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }

}
