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

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.View
import androidx.viewpager.widget.ViewPager
import com.android.volley.NoConnectionError
import com.android.volley.TimeoutError
import com.android.volley.VolleyError
import com.seatel.mobilehall.R
import com.seatel.mobilehall.databinding.ActivityPromotionBinding
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.adapter.PromotionAdapter
import com.seatel.mobilehall.ui.home.interactor.PromotionsInteractor
import com.seatel.mobilehall.ui.home.model.PromotionListModel
import com.seatel.mobilehall.ui.home.presenter.PromotionsPresenter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.customview.ErrorHandleView
import java.util.TimerTask

class PromotionActivity : BaseActivity<ActivityPromotionBinding>(), PromotionsInteractor.View {

    private var handler: Handler? = null
    private var handlerAutoSlide: Handler? = null
    private lateinit var adapterPromotion: PromotionAdapter
    private lateinit var mPromotionList: ArrayList<PromotionListModel>
    private var firstStart = true
    private var mPromotionsPresenter: PromotionsPresenter? = null

    override fun onGetPromotionSucceed(promotionList: ArrayList<PromotionListModel>) {
        mPromotionList = promotionList
        initViews(promotionList)
        if (promotionList.size == 0) {
            binding.errorView.errorMessage = getString(R.string.no_promotion)
            binding.errorView.setViewMode(ErrorHandleView.Mode.NO_DATA)
            binding.pageIndicator.visibility = View.GONE
        }
    }

    override fun onGetPromotionFailed(error: VolleyError) {
        binding.errorView.visibility = View.GONE
        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 -> {
                binding.errorView.errorMessage = getString(R.string.no_promotion)
                binding.errorView.setViewMode(ErrorHandleView.Mode.NO_DATA)
            }
        }
        binding.pageIndicator.visibility = View.GONE
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityEnterRightAnimation()
     //   setContentView(R.layout.activity_promotion)
        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
        mPromotionsPresenter = PromotionsPresenter(this)
        mPromotionsPresenter?.onGetPromotion(getPhoneLogin())
        adapterPromotion = PromotionAdapter(this)
    }

    override fun onResume() {
        super.onResume()
        start()
    }

    override fun onPause() {
        super.onPause()
        stopHandler()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPromotionsPresenter?.onDestroy()
        stopHandler()
    }

    fun start() {
        if (handler == null) {
            handler = Handler(Looper.getMainLooper())
            handler!!.postDelayed(runnable, 4000)
        }
    }

    private fun stopHandler() {

        if (handler != null) {
            handler!!.removeCallbacks(runnable)
        }

    }

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

    private fun initViews(promotionList: ArrayList<PromotionListModel>) {
        adapterPromotion.setData(createPageList(promotionList))
        binding.viewpagerDevice.adapter = adapterPromotion
        adapterPromotion.setItemClick(this)
        binding.pageIndicator.pageCount = promotionList.size
        binding.viewpagerDevice.setPageTransformer(false, FadePageTransformer())
        binding.viewpagerDevice.currentItem = 0
        binding.viewpagerDevice.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            private var jumpPosition = -1
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                if (position == 0) {
                    //prepare to jump to the last page
                    jumpPosition = adapterPromotion.realCount

                    //TODO: indicator.setActive(adapter.getRealCount() - 1)
                    binding.pageIndicator.setCurrentPage(adapterPromotion.realCount - 1, true)
                } else if (position == adapterPromotion.realCount + 1) {
                    //prepare to jump to the first page
                    jumpPosition = 1

                    //TODO: indicator.setActive(0)
                    binding.pageIndicator.setCurrentPage(0, true)
                } else {
                    //TODO: indicator.setActive(position - 1)

                    binding.pageIndicator.setCurrentPage(position - 1, true)
                }

//                val newPost = position % promotionList.size

            }

            override fun onPageScrollStateChanged(state: Int) {

                if (state == 1) {
                    stopHandler()
                    setSwitchingDuration(5.0)
//                    if (binding.viewpagerDevice.background != null)
//                        binding.viewpagerDevice.background = null
                } else if (state == 0) {
                    handler = null
                    start()
                    setSwitchingDuration(10.0)
                }
                if ((state == ViewPager.SCROLL_STATE_IDLE) and (jumpPosition >= 0)) {
                    //Jump without animation so the user is not aware what happened.
                    binding.viewpagerDevice.setCurrentItem(jumpPosition, false)
                    //Reset jump position.
                    jumpPosition = -1
                }

            }
        })

        binding.errorView.visibility = View.GONE
        if (handlerAutoSlide == null) {
            handlerAutoSlide = Handler()
            handlerAutoSlide!!.postDelayed({
                start()
            }, 2000)
        }
    }

    private fun createPageList(promotionList: ArrayList<PromotionListModel>): List<String> {
        val pageList = ArrayList<String>()
        for (i in 0 until promotionList.size) {
            pageList.add(promotionList[i].getBanner())
        }
        return pageList
    }


    override fun onItemClick(index: String) {
        stopHandler()
        showDetailScreen(index)
    }

    private fun showDetailScreen(index: String) {
        val data = mPromotionList[index.toInt()]
        val typePromotion = data.getPromotionType()
        when (typePromotion) {
            Constant.DEVICE -> {
                if ((TextUtils.equals(
                        data.getUrl().toLowerCase(),
                        "all"
                    )) || TextUtils.isEmpty(data.getUrl())
                ) {
                    //  DeviceActivity.lunch(this)
                    // FirebaseAnalyticsUtil.getInstance(this).logCustomEvent(Constant.SeaTelAnalytics.Value.GET_PROMOTION_DEVICE)
                } else {
                    DeviceDetailActivity.launch(this, data.getUrl(), "")
                }
            }

            Constant.PRODUCT -> {
                if ((TextUtils.equals(
                        data.getUrl().toLowerCase(),
                        "all"
                    )) || TextUtils.isEmpty(data.getUrl())
                ) {
                    ProductServiceActivity.lunch(this)
                } else {
                    showProductDetail(data.getUrl())
                    //   FirebaseAnalyticsUtil.getInstance(this).logCustomEvent(Constant.SeaTelAnalytics.Value.GET_PROMOTION_PRODUCT)
                }
            }

            Constant.LINK -> {
                if (!TextUtils.isEmpty(data.getUrl())) {
                    val uris = Uri.parse(data.getUrl())
                    val intents = Intent(Intent.ACTION_VIEW, uris)
                    intents.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    val b = Bundle()
                    b.putBoolean("new_window", true)
                    intents.putExtras(b)
                    applicationContext.startActivity(intents)
                }
            }

            Constant.YES_PROMOTION -> {
                  BuyYesNumberPhaseTwoActivity.lunch(this, true)
            }
        }
    }

    private fun showProductDetail(productType: String) {
        when (productType) {
            Constant.ONE_PLAN -> {
                //  OnePlanDetailActivity.lunch(this)
            }

            Constant.INTERNET_PACK -> {
                // InternetPackActivity.lunch(this)
            }

            Constant.FREE_INTERNET -> {
                //   FreePromotionDetailActivity.lunch(this, getString(R.string.free_internet_promotion))
            }

            Constant.UNLIMITED_YOUTUBE -> {
                //   FreeUnlimitedYouTubeActivity.lunch(this)
            }

            Constant.VALUE_PACK -> {
                //   ValuePackActivity.lunch(this)
            }
        }
    }

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

    override fun getToolbarTitle(): String {
        return getString(R.string.promotions)
    }

    private val runnable = Runnable {
        try {
            runOnUiThread(object : TimerTask() {
                override fun run() {
//                    binding.viewpagerDevice.clearOnPageChangeListeners()
                    if (firstStart) {
                        firstStart = false
                        binding.viewpagerDevice.setCurrentItem(
                            binding.viewpagerDevice.currentItem + 2,
                            true
                        )
                    } else
                        binding.viewpagerDevice.setCurrentItem(
                            binding.viewpagerDevice.currentItem + 1,
                            true
                        )

                }
            })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    inner class FadePageTransformer : ViewPager.PageTransformer {
        override fun transformPage(view: View, position: Float) {
            view.translationX = view.width * -position
            if (position <= -1.0f || position >= 1.0f) {
                view.alpha = 0.0f
                view.translationX = view.width * (-position + 1)
            } else if (position == 0.0f) {
                view.alpha = 1.0f
            } else {
                view.alpha = 1.0f - Math.abs(position)
            }
        }
    }

    fun setSwitchingDuration(switchingDuration: Double) {
        binding.viewpagerDevice.setScrollDurationFactor(switchingDuration)
    }

}
