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

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.animation.AnimationUtils
import android.view.animation.LayoutAnimationController
import androidx.recyclerview.widget.LinearLayoutManager
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.FAQsAdapter
import com.seatel.mobilehall.ui.home.adapter.SupportListAdapter
import com.seatel.mobilehall.ui.home.adapter.SupportedDeviceDetailAdapter
import com.seatel.mobilehall.ui.home.interactor.FAQsInteractor
import com.seatel.mobilehall.ui.home.interactor.ItemViewInteractor
import com.seatel.mobilehall.ui.home.interactor.SupportedDeviceInteractor
import com.seatel.mobilehall.ui.home.model.FAQModel
import com.seatel.mobilehall.ui.home.model.SupportedDeviceModel
import com.seatel.mobilehall.ui.home.presenter.FAQsPresenter
import com.seatel.mobilehall.ui.home.presenter.SupportedDevicePresenter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelUtils
import com.paginate.Paginate
import com.paginate.recycler.LoadingListItemSpanLookup
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.util.customview.ErrorHandleView
import kotlinx.android.synthetic.main.activity_support_list.*


class SupportListActivity : BaseActivity(), SupportedDeviceInteractor.View, ItemViewInteractor,
    View.OnClickListener, FAQsInteractor.View {

    private lateinit var presenter: SupportedDeviceInteractor.Presenter
    private var supportedDeviceList: ArrayList<SupportedDeviceModel> = ArrayList()
    private val animId = R.anim.layout_slide_from_bottom
    private lateinit var animation: LayoutAnimationController
    private var supportedDeviceDetailList: ArrayList<String> = ArrayList()
    private var isSearchName = false
    private var isSupportedDevice = false
    private var isFaq = false
    private var offset = 0
    private var LIMIT_OFF_SET = 10
    private lateinit var faqsPresenter: FAQsPresenter
    private lateinit var supportLisAdapter: SupportListAdapter
    private lateinit var supportedDeviceDetailAdapter: SupportedDeviceDetailAdapter
    private lateinit var faqAdapter: FAQsAdapter
    private lateinit var faqList: ArrayList<FAQModel>
    private var isLoading = false
    private var isLoadAll = false
    private lateinit var paginate: Paginate

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_support_list)
        activityEnterRightAnimation()
        init()
    }

    override fun responseSucceedSupportedDeviceData(supportedDeviceList: ArrayList<SupportedDeviceModel>) {

        this.supportedDeviceList.clear()
        this.supportedDeviceList.addAll(supportedDeviceList)
        supportLisAdapter = SupportListAdapter(this, this.supportedDeviceList, this)
        rv_support_list.adapter = supportLisAdapter
        hideProgress()
        /*paginate.unbind()
        paginate.setHasMoreDataToLoad(false)*/
    }

    override fun responseFailed(error: VolleyError) {
        paginate.setHasMoreDataToLoad(false)
        hideProgress()
        rv_support_list.visibility = View.GONE
        error_view.visibility = View.VISIBLE
        when (error) {
            is NoConnectionError -> {
                error_view.errorMessage = getString(R.string.connection_timeout)
                error_view.setViewMode(ErrorHandleView.Mode.NO_INTERNET)
            }
            is TimeoutError -> {
                error_view.errorMessage = getString(R.string.fetch_supported_device_data)
                error_view.setViewMode(ErrorHandleView.Mode.TIME_OUT)
            }
            else -> {
                error_view.errorMessage = SeatelSuperRequest.getErrorMessageFrom(error)
                error_view.setViewMode(ErrorHandleView.Mode.NO_DATA)
            }
        }
    }

    fun getFAQsDefaultList() {
        faqList.clear()
        faqAdapter.notifyDataSetChanged()
        faqsPresenter.onLoadData("", 0)


    }

    private fun init() {

        val titleToolBar: String =
            intent.getStringExtra(Constant.SUPPORT_IDENTIFY).toString()
        setUpToolbarTitle(titleToolBar)

        image_clear.setOnClickListener(this)
        animation = AnimationUtils.loadLayoutAnimation(this, animId)
        rv_support_list.layoutManager = LinearLayoutManager(this)
        rv_support_list.layoutAnimation = animation
        supportedDeviceDetailList =
            intent.getStringArrayListExtra(Constant.SUPPORTED_DEVICE_DETAIL)!!
        faqsPresenter = FAQsPresenter(this)


        //faq recycler view staff
        faqList = ArrayList()
        faqAdapter = FAQsAdapter(this, faqList)
        rv_support_list.layoutManager = LinearLayoutManager(this@SupportListActivity)
        rv_support_list.layoutAnimation = this@SupportListActivity.animation
        rv_support_list.adapter = faqAdapter


        if (supportedDeviceDetailList.size == 0) {

            if (titleToolBar == Constant.EXTRA_FAQ) {
                getFAQsDefaultList()
                isFaq = true
                paginate = Paginate.with(rv_support_list, callbacks)
                    .setLoadingTriggerThreshold(2)
                    .addLoadingListItem(true)
                    .setLoadingListItemCreator(null)
                    .setLoadingListItemSpanSizeLookup(LoadingListItemSpanLookup { 5 })
                    .build()
            } else {
                presenter = SupportedDevicePresenter(this)
                presenter.onLoadData()
                isSupportedDevice = true
                showProgress()
            }

        } else {
            supportedDeviceDetailAdapter =
                SupportedDeviceDetailAdapter(this, supportedDeviceDetailList)
            rv_support_list.adapter = supportedDeviceDetailAdapter
            isSearchName = true
            isSupportedDevice = true
        }
        onSearchAndAnimateEdittext()

        /*paginate = Paginate.with(rv_support_list, callbacks)
                .setLoadingTriggerThreshold(2)
                .addLoadingListItem(true)
                .setLoadingListItemCreator(null)
                .setLoadingListItemSpanSizeLookup(LoadingListItemSpanLookup { 5 })
                .build()*/
        //paginate.setHasMoreDataToLoad(!intent.getBooleanExtra(Constant.IntentKeys.SEARCH_DEVICE, false))

    }

    private var callbacks: Paginate.Callbacks = object : Paginate.Callbacks {
        override fun onLoadMore() {
            if (this@SupportListActivity.isLoading) {
                offset += LIMIT_OFF_SET
                faqsPresenter.onLoadData("", offset)
                this@SupportListActivity.isLoading = false

            }
        }

        override fun isLoading(): Boolean {
            // Indicate whether new page loading is in progress or not
            return false
        }

        override fun hasLoadedAllItems(): Boolean {
            // Indicate whether all data (pages) are loaded or not
            return isLoading
        }

    }
    var a = 1
    private fun onSearchAndAnimateEdittext() {
        cet_search.apply {
            onFocusChangeListener = View.OnFocusChangeListener { _, _ ->
                animateSearch()

                addTextChangedListener(object : TextWatcher {
                    override fun afterTextChanged(s: Editable?) {}

                    override fun beforeTextChanged(
                        s: CharSequence?,
                        start: Int,
                        count: Int,
                        after: Int
                    ) {
                    }

                    override fun onTextChanged(
                        string: CharSequence?,
                        start: Int,
                        before: Int,
                        count: Int
                    ) {
                        if (TextUtils.isEmpty(string)) {
                            image_clear.visibility = View.INVISIBLE
                            fake_hint.visibility = View.VISIBLE
                            error_view.visibility = View.GONE

                            if (isSearchName && isSupportedDevice) {
                                rv_support_list.layoutManager =
                                    LinearLayoutManager(this@SupportListActivity)
                                rv_support_list.layoutAnimation = this@SupportListActivity.animation
                                supportedDeviceDetailAdapter = SupportedDeviceDetailAdapter(
                                    applicationContext,
                                    supportedDeviceDetailList
                                )
                                rv_support_list.adapter = supportedDeviceDetailAdapter
                            } else if (isFaq) {
                                getFAQsDefaultList()
                            } else if (isSupportedDevice) {
                                rv_support_list.layoutManager =
                                    LinearLayoutManager(this@SupportListActivity)
                                rv_support_list.layoutAnimation = this@SupportListActivity.animation
                                supportLisAdapter = SupportListAdapter(
                                    applicationContext,
                                    supportedDeviceList,
                                    this@SupportListActivity
                                )
                                rv_support_list.adapter = supportLisAdapter
                            }

                        } else {
                            fake_hint.visibility = View.INVISIBLE
                            image_clear.visibility = View.VISIBLE

                            //search supported device by name
                            if (isSearchName && isSupportedDevice) {
                                val searchSupportedDeviceDetail = ArrayList<String>()
                                supportedDeviceDetailList.forEach {
                                    if (it.toLowerCase().contains(string.toString())) {
                                        searchSupportedDeviceDetail.add(it)
                                    }
                                }
                                if (searchSupportedDeviceDetail.isEmpty()) {
                                    error_view.visibility = View.VISIBLE
                                    error_view.setViewMode(ErrorHandleView.Mode.NO_DATA)
                                } else error_view.visibility = View.GONE
                                rv_support_list.layoutManager =
                                    LinearLayoutManager(this@SupportListActivity)
                                rv_support_list.layoutAnimation = this@SupportListActivity.animation
                                supportedDeviceDetailAdapter = SupportedDeviceDetailAdapter(
                                    applicationContext,
                                    searchSupportedDeviceDetail
                                )
                                rv_support_list.adapter = supportedDeviceDetailAdapter

                            }
                            //search supported device by brand
                            else if (isSupportedDevice) {
                                val searchSupportDevice = ArrayList<SupportedDeviceModel>()
                                supportedDeviceList.forEach {
                                    if (it.brand?.toLowerCase()!!.contains(string.toString())) {
                                        searchSupportDevice.add(it)
                                    }
                                }
                                if (searchSupportDevice.isEmpty()) {
                                    error_view.visibility = View.VISIBLE
                                    error_view.setViewMode(ErrorHandleView.Mode.NO_DATA)
                                } else error_view.visibility = View.GONE
                                rv_support_list.layoutManager =
                                    LinearLayoutManager(this@SupportListActivity)
                                rv_support_list.layoutAnimation = this@SupportListActivity.animation
                                supportLisAdapter = SupportListAdapter(
                                    applicationContext,
                                    searchSupportDevice,
                                    this@SupportListActivity
                                )
                                rv_support_list.adapter = supportLisAdapter
                            } else if (isFaq) {
                                offset = 0
                                faqList.clear()
                                faqAdapter.notifyDataSetChanged()
                                faqsPresenter.onLoadData(string.toString(), offset)
                            }
                        }
                    }
                })
            }
        }
    }

    override fun responseSucceedFAQsData(faqList: ArrayList<FAQModel>, totalCount: Int) {

        this.faqList.addAll(faqList)
        faqAdapter.notifyItemChanged(this.faqList.size - faqList.size)


        if (faqList.isEmpty() || totalCount <= this.faqList.size || totalCount <= faqList.size) {
            isLoadAll = true
            isLoading = false
            paginate.unbind()
            paginate.setHasMoreDataToLoad(false)

        } else {
            isLoadAll = false
            isLoading = true


        }


        //check is data empty
        if (this.faqList.size == 0) {
            error_view.visibility = View.VISIBLE
            error_view.setViewMode(ErrorHandleView.Mode.NO_DATA)
            rv_support_list.visibility = View.GONE
        } else {
            error_view.visibility = View.GONE
            rv_support_list.visibility = View.VISIBLE
        }

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.image_clear -> {
                cet_search.setText("")
            }
        }
    }

    override fun onClick(view: View, position: Int) {
        val supportedDeviceDetailList = ArrayList<String>()
        supportedDeviceList[position].devices!!.forEach {
            supportedDeviceDetailList.add(it.name!!)
        }
        SupportListActivity.lunch(
            this,
            true,
            Constant.EXTRA_SUPPORTED_DEVICE,
            supportedDeviceDetailList
        )

    }

    fun setUpToolbarTitle(title: String) {

        if (TextUtils.isEmpty(title))
            setToolbarTitle(getString(R.string.support))
        else {
            if (title.equals(Constant.EXTRA_FAQ)) {
                setToolbarTitle(getString(R.string.faqs))
                fake_hint.text = getString(R.string.search_faqs)
            } else {
                setToolbarTitle(getString(R.string.supported_device))
                val isSearchDevice =
                    intent.getBooleanExtra(Constant.SEARCH_DEVICE, false)
                if (isSearchDevice)
                    fake_hint.text = getString(R.string.search_device)
                else fake_hint.text = getString(R.string.search_device_brand)
            }
        }
    }

    override fun isDisplayToolbar(): Boolean {
        return true
    }

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

    private fun animateSearch() {
        var width = layout_search.width / 2
        val viewSearchWidth = view_search.width / 2
        width = width - viewSearchWidth - SeatelUtils.convertDpToPx(this@SupportListActivity, 10)
        width = -width
        view_search.animate().translationX(width.toFloat()).duration = 300
    }

    companion object {
        fun lunch(context: Context, isSearchDevice: Boolean, identify: String, list: List<String>) {
            val intent = Intent(context, SupportListActivity::class.java)
            intent.putExtra(Constant.SUPPORT_IDENTIFY, identify)
            intent.putExtra(Constant.SEARCH_DEVICE, isSearchDevice)
            intent.putStringArrayListExtra(
                Constant.SUPPORTED_DEVICE_DETAIL,
                list as ArrayList<String>
            )
            context.startActivity(intent)
        }
    }


}
