package com.gh.gamecenter.feedback.view.help

import android.content.Context
import android.os.Handler
import android.os.Message
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.therouter.TheRouter
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.feedback.R
import com.gh.gamecenter.feedback.databinding.ItemHelpVideoBinding
import com.gh.gamecenter.feedback.entity.HelpVideo
import com.lightgame.adapter.BaseRecyclerAdapter
import java.lang.ref.WeakReference

class HelpVideoAdapter(
    context: Context,
    private val mLifecycleOwner: LifecycleOwner,
    private val mSnapHelper: LeftPagerSnapHelper,
    private val mLayoutManager: LinearLayoutManager,
    private val mRecyclerView: RecyclerView
) : BaseRecyclerAdapter<RecyclerView.ViewHolder>(context) {
    private var mHelpVideoList = arrayListOf<HelpVideo>()
    private val mLooperHandle = LooperHandle(this)
    private val mSlideLooperKey = 102
    private val mLifecycleObserver = object : DefaultLifecycleObserver {
        override fun onResume(owner: LifecycleOwner) {
            super.onResume(owner)
            startScroll()
        }

        override fun onPause(owner: LifecycleOwner) {
            super.onPause(owner)
            stopScroll()
        }
    }

    fun submitList(helpVideoList: List<HelpVideo>) {
        mHelpVideoList = ArrayList(helpVideoList)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return HelpVideoItemViewHolder(parent.toBinding())
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is HelpVideoItemViewHolder) {
            val actualPosition = getActualPosition(position)
            val helpVideo = mHelpVideoList.safelyGetInRelease(actualPosition) ?: return
            holder.binding.run {
                root.layoutParams = (root.layoutParams as MarginLayoutParams).apply {
                    leftMargin = 16F.dip2px()
                    rightMargin = if (position == itemCount - 1) mRecyclerView.width - 240F.dip2px() - leftMargin else 0
                }
                videoTitleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(mContext))
                videoDesTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext))

                videoTitleTv.text = helpVideo.title
                videoDesTv.text = helpVideo.description
                ImageUtils.display(videoCoverIv, helpVideo.video?.poster)
                labelIv.goneIf(helpVideo.recommendType.isEmpty() || helpVideo.recommendType == "none") {
                    labelIv.setImageResource(
                        when (helpVideo.recommendType) {
                            "new" -> R.drawable.label_new
                            "hot" -> R.drawable.label_hot
                            "activity" -> R.drawable.label_activity
                            "notice" -> R.drawable.label_announcement
                            else -> return@goneIf
                        }
                    )
                }

                root.setOnClickListener {
                    TheRouter.build(RouteConsts.activity.fullScreenVideoActivity)
                        .withString(EntranceConsts.KEY_URL, helpVideo.video?.url)
                        .withString(EntranceConsts.KEY_POSTER_PATH, helpVideo.video?.poster)
                        .withString(EntranceConsts.KEY_NAVIGATION_TITLE, "帮助视频")
                        .withBoolean(EntranceConsts.KEY_IS_QA_FEEDBACK, true)
                        .withString(EntranceConsts.KEY_ID, helpVideo.id)
                        .withString(EntranceConsts.KEY_QA_TITLE, helpVideo.title)
                        .withString(EntranceConsts.KEY_VIDEO_ID, helpVideo.video?.id)
                        .withInt(EntranceConsts.KEY_VIDEO_LENGTH, helpVideo.video?.length ?: 0)
                        .withInt(EntranceConsts.KEY_SEQUENCE, actualPosition)
                        .withBoolean(EntranceConsts.KEY_IS_LANDSCAPE, false)
                        .withBoolean(EntranceConsts.KEY_VIDEO_MUTE, false)
                        .navigation()
                }
            }
        }
    }

    override fun getItemCount(): Int = if (mHelpVideoList.size < 3) mHelpVideoList.size else Int.MAX_VALUE

    fun getActualPosition(position: Int): Int {
        var actualPosition = position
        if (mHelpVideoList.size in 1..position) {
            actualPosition = position % mHelpVideoList.size
        }
        return actualPosition
    }

    fun getActualFirstPositionInCenter(): Int {
        var index = itemCount / 2
        while (getActualPosition(index) != 0) {
            index++
        }
        return index
    }

    class HelpVideoItemViewHolder(val binding: ItemHelpVideoBinding) : BaseRecyclerViewHolder<Any>(binding.root)

    fun scrollToNextPage() {
        if (itemCount > 2) {
            mSnapHelper.findSnapView(mLayoutManager)?.let {
                val position = mLayoutManager.getPosition(it)
                mRecyclerView.scrollToPositionWithTop(position + 1)
                startScroll()
            }
        }
    }

    fun startScroll() {
        mLooperHandle.removeMessages(mSlideLooperKey)
        mLooperHandle.sendEmptyMessageDelayed(mSlideLooperKey, SLIDE_DELAY)
    }

    fun stopScroll() {
        mLooperHandle.removeMessages(mSlideLooperKey)
    }

    override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder) {
        super.onViewAttachedToWindow(holder)
        mLifecycleOwner.lifecycle.addObserver(mLifecycleObserver)
    }

    override fun onViewDetachedFromWindow(holder: RecyclerView.ViewHolder) {
        super.onViewDetachedFromWindow(holder)
        mLifecycleOwner.lifecycle.removeObserver(mLifecycleObserver)
    }

    class LooperHandle(adapter: HelpVideoAdapter) : Handler() {
        private val mWeakReference: WeakReference<HelpVideoAdapter> = WeakReference(adapter)

        override fun handleMessage(msg: Message) {
            val adapter = mWeakReference.get()
            if (adapter != null) {
                if (msg.what == adapter.mSlideLooperKey) {
                    adapter.scrollToNextPage()
                }
            }
        }
    }

    companion object {
        private const val SLIDE_DELAY = 5000L
    }
}