package com.gh.vspace

import android.content.Context
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.gh.common.util.NewFlatLogUtils
import com.gh.download.DownloadManager
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.DiffUtilAdapter
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.GridSpacingItemColorDecoration
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.ItemHomeRecentVgameBinding
import com.gh.gamecenter.databinding.ItemHomeVgameBinding
import com.gh.gamecenter.manager.PackagesManager
import com.lightgame.download.DownloadEntity
import com.lightgame.download.DownloadStatus

class HomeRecentVGameViewHolder(var binding: ItemHomeRecentVgameBinding) :
    RecyclerView.ViewHolder(binding.root) {

    fun bindView(entityList: ArrayList<VGameItemData>) {
        if (binding.recyclerView.adapter == null) {
            val layoutManager =
                LinearLayoutManager(binding.root.context, RecyclerView.HORIZONTAL, false)

            binding.recyclerView.layoutManager = layoutManager
            binding.recyclerView.itemAnimator = null
            binding.recyclerView.adapter = HomeRecentVGameAdapter(binding.root.context)
            binding.recyclerView.addItemDecoration(
                GridSpacingItemColorDecoration(binding.root.context, 4, 0, R.color.transparent)
            )

            binding.recyclerView.addOnScrollListener(object : OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    val scrollToEnd =
                        layoutManager.findLastCompletelyVisibleItemPosition() == (binding.recyclerView.adapter!!.itemCount - 1)
                    binding.divider.visibleIf(scrollToEnd)
                }
            })

            binding.moreTv.setOnClickListener {
                NewFlatLogUtils.logHaloFunManageShow("最近在玩")
                binding.root.context.startActivity(
                    VDownloadManagerActivity.getIntent(
                        binding.root.context,
                        switchToDownloadingTab = false,
                        isFromHomeRecent = true
                    )
                )
            }

            binding.vspaceIv.setOnClickListener {
                NewFlatLogUtils.logHaloFunEvent("halo_fun_manage_square_entrance_click")
                VHelper.startVSpaceSquare(it.context)
            }
        }

        (binding.recyclerView.adapter as? HomeRecentVGameAdapter)?.submitList(entityList)
    }
}

class HomeRecentVGameAdapter(context: Context) : DiffUtilAdapter<VGameItemData>(context) {

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

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        (holder as HomeRecentVGameItemViewHolder).bindView(mDataList[position])
    }

    override fun getItemCount(): Int {
        return mDataList.size
    }

    fun notifyItemByDownload(downloadEntity: DownloadEntity?) {
        if (downloadEntity == null) {
            notifyDataSetChanged()
        } else {
            for (position in mDataList.indices) {
                if (downloadEntity.name == mDataList[position].downloadEntity.name) {
                    mDataList[position].downloadEntity = downloadEntity
                    notifyItemChanged(position)
                }
            }
        }
    }

    override fun areItemsTheSame(oldItem: VGameItemData?, newItem: VGameItemData?): Boolean {
        return oldItem == newItem
    }

    override fun areContentsTheSame(oldItem: VGameItemData?, newItem: VGameItemData?): Boolean {
        // VGameItemData 里除了 downloadEntity 以外的内容仅作是否内容发生变更的判断，
        // 并不应用到实际状态当中，最后还是得从 downloadEntity 里实时获取判断，
        // 别问，问就是下载管理跟实际列表更新两边很难扯在一起

        return oldItem?.downloadEntity == newItem?.downloadEntity
                && oldItem?.shouldShowControlTv == newItem?.shouldShowControlTv
                && oldItem?.shouldShowDot == newItem?.shouldShowDot
                && oldItem?.shouldShowMask == newItem?.shouldShowMask
                && oldItem?.shouldShowUpdate == newItem?.shouldShowUpdate
                && oldItem?.shouldShowProgressBar == newItem?.shouldShowProgressBar
    }

    class HomeRecentVGameItemViewHolder(private var mBinding: ItemHomeVgameBinding) :
        RecyclerView.ViewHolder(mBinding.root) {

        fun bindView(entity: VGameItemData) {
            if (mBinding.gameIconIv.getTag(R.string.app_name) != entity.downloadEntity.packageName) {
                mBinding.gameIconIv.displayGameIcon(
                    entity.downloadEntity.getMetaExtra(Constants.RAW_GAME_ICON),
                    entity.downloadEntity.getMetaExtra(Constants.GAME_ICON_SUBSCRIPT)
                )
                mBinding.gameIconIv.setTag(R.string.app_name, entity.downloadEntity.packageName)
            }

            updateViewByStatus(mBinding, entity)
        }

        private fun updateViewByStatus(binding: ItemHomeVgameBinding, itemData: VGameItemData) {
            val downloadEntity = itemData.downloadEntity

            itemData.refresh()

            when (downloadEntity.status) {
                DownloadStatus.done -> {
                    if (itemData.shouldShowUpdate) {
                        binding.root.setOnClickListener {
                            PackagesManager.getUpdateList()
                                .firstOrNull { it.id == downloadEntity.gameId }
                                ?.let {
                                    VHelper.updateOrReDownload(downloadEntity, it)
                                }
                        }
                    } else {
                        binding.root.setOnClickListener {
                            VHelper.installOrLaunch(
                                binding.root.context,
                                downloadEntity.packageName
                            )
                        }
                    }
                }
                DownloadStatus.subscribe,
                DownloadStatus.waiting,
                DownloadStatus.pause -> {
                    binding.progressBar.progressDrawable =
                        R.drawable.bg_home_vgame_progress_inactive.toDrawable()

                    if (downloadEntity.status == DownloadStatus.waiting) {
                        binding.root.setOnClickListener {
                            ToastUtils.toast("最多只能同时下载三个任务，请稍等")
                        }
                    } else {
                        binding.root.setOnClickListener {
                            DownloadManager.getInstance().resume(downloadEntity, false)
                        }
                    }
                }
                DownloadStatus.redirected,
                DownloadStatus.downloading -> {
                    binding.progressBar.progressDrawable =
                        R.drawable.bg_home_vgame_progress_active.toDrawable()
                    binding.root.setOnClickListener {
                        DownloadManager.getInstance().pause(downloadEntity.url)
                    }
                }

                DownloadStatus.cancel,
                DownloadStatus.timeout,
                DownloadStatus.neterror,
                DownloadStatus.hijack,
                DownloadStatus.uncertificated,
                DownloadStatus.unqualified,
                DownloadStatus.notfound,
                DownloadStatus.unavailable,
                DownloadStatus.overflow -> {
                    binding.root.setOnClickListener {
                        DownloadManager.getInstance().resume(downloadEntity, false)
                    }
                }
                else -> {
                    binding.root.setOnClickListener {
                        ToastUtils.showToast(downloadEntity.status.toString())
                    }
                }
            }

            mBinding.maskView.goneIf(!itemData.shouldShowMask)
            mBinding.controlTv.goneIf(!itemData.shouldShowControlTv)
            mBinding.progressBar.goneIf(!itemData.shouldShowProgressBar)
            mBinding.dotView.goneIf(!itemData.shouldShowDot)
            mBinding.updateHintIv.goneIf(!itemData.shouldShowUpdate)

            mBinding.controlTv.text = itemData.controlText
            mBinding.progressBar.progress = downloadEntity.percent.toInt()
        }
    }
}
