package com.gh.gamecenter.home.custom.adapter

import android.content.Context
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.download.DownloadManager
import com.gh.gamecenter.R
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.entity.IconFloat
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.ItemHomeVgameRefactorBinding
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.IExposureProvider
import com.gh.gamecenter.home.custom.eventlistener.OtherItemEventHelper
import com.gh.gamecenter.manager.PackagesManager
import com.gh.vspace.VGameItemData
import com.gh.vspace.VHelper
import com.lightgame.download.DownloadEntity
import com.lightgame.download.DownloadStatus

class CustomHomeRecentVGameAdapter(
    context: Context,
    private val childEventHelper: OtherItemEventHelper
) : CustomBaseChildAdapter<VGameItemData, CustomHomeRecentVGameAdapter.HomeRecentVGameItemViewHolder>(context) {

    override fun getKey(t: VGameItemData): String {
        return t.downloadEntity.gameId
    }

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

    override fun onBindViewHolder(holder: HomeRecentVGameItemViewHolder, position: Int) {
        (holder as? HomeRecentVGameItemViewHolder)?.bindView(dataList[position])
    }

    override fun getItemCount(): Int = dataList.size

    override fun notifyDownload(download: DownloadEntity) {
        dataList.forEachIndexed { position, item ->
            if (download.name == item.downloadEntity.name) {
                item.downloadEntity = download
                notifyItemChanged(position)
            }
        }
    }

    class HomeRecentVGameItemViewHolder(
        private var binding: ItemHomeVgameRefactorBinding,
        private val childEventHelper: OtherItemEventHelper
    ) :
        RecyclerView.ViewHolder(binding.root), IExposureProvider {

        private var boundedItem: VGameItemData? = null

        fun bindView(entity: VGameItemData) {
            boundedItem = entity

            if (binding.gameIconIv.getTag(R.string.app_name) != entity.downloadEntity.packageName) {
                val iconFloat = IconFloat(
                    entity.downloadEntity.getMetaExtra(Constants.GAME_ICON_FLOAT_TOP_TEXT),
                    entity.downloadEntity.getMetaExtra(Constants.GAME_ICON_FLOAT_TOP_COLOR),
                    entity.downloadEntity.getMetaExtra(Constants.GAME_ICON_FLOAT_BOTTOM_TEXT)
                )
                binding.gameIconIv.displayGameIcon(
                    entity.downloadEntity.getMetaExtra(Constants.RAW_GAME_ICON),
                    entity.downloadEntity.getMetaExtra(Constants.GAME_ICON_SUBSCRIPT),
                    iconFloat
                )
                binding.gameIconIv.setTag(R.string.app_name, entity.downloadEntity.packageName)
            }

            updateViewByStatus(binding, entity, childEventHelper)
        }

        private fun updateViewByStatus(
            binding: ItemHomeVgameRefactorBinding,
            itemData: VGameItemData,
            childEventHelper: OtherItemEventHelper
        ) {
            val downloadEntity = itemData.downloadEntity

            itemData.refresh()

            when (downloadEntity.status) {
                DownloadStatus.done -> {
                    if (itemData.shouldShowUpdate) {
                        binding.root.setOnClickListener {
                            childEventHelper.trackCWRecentlyPlayedClick("游戏", downloadEntity)
                            PackagesManager.getUpdateList()
                                .firstOrNull { it.id == downloadEntity.gameId }
                                ?.let {
                                    VHelper.updateOrReDownload(downloadEntity, it)
                                }
                        }
                    } else {
                        binding.root.setOnClickListener {
                            childEventHelper.trackCWRecentlyPlayedClick("游戏", downloadEntity)
                            if (!VHelper.isInstalled(downloadEntity.packageName)) {
                                NewFlatLogUtils.logGameInstall(
                                    downloadEntity.gameId,
                                    downloadEntity.name,
                                    "主动安装"
                                )

                                SensorsBridge.trackInstallGameClick(
                                    downloadEntity.gameId,
                                    downloadEntity.name,
                                    "主动安装"
                                )
                            }
                            VHelper.installOrLaunch(binding.root.context, downloadEntity, "最近在玩-图标")
                        }
                    }
                }

                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 {
                            childEventHelper.trackCWRecentlyPlayedClick("游戏", downloadEntity)
                            ToastUtils.toast("最多只能同时下载三个任务，请稍等")
                        }
                    } else {
                        binding.root.setOnClickListener {
                            childEventHelper.trackCWRecentlyPlayedClick("游戏", downloadEntity)
                            DownloadManager.getInstance().resume(downloadEntity, false)
                        }
                    }
                }

                DownloadStatus.redirected,
                DownloadStatus.downloading -> {
                    binding.progressBar.progressDrawable =
                        R.drawable.bg_home_vgame_progress_active.toDrawable()
                    binding.root.setOnClickListener {
                        childEventHelper.trackCWRecentlyPlayedClick("游戏", downloadEntity)
                        DownloadManager.getInstance().pause(downloadEntity.url)
                    }
                }

                DownloadStatus.cancel,
                DownloadStatus.timeout,
                DownloadStatus.neterror,
                DownloadStatus.hijack,
                DownloadStatus.uncertificated,
                DownloadStatus.unqualified,
                DownloadStatus.notfound,
                DownloadStatus.diskisfull,
                DownloadStatus.diskioerror,
                DownloadStatus.unavailable,
                DownloadStatus.overflow -> {
                    binding.root.setOnClickListener {
                        childEventHelper.trackCWRecentlyPlayedClick("游戏", downloadEntity)
                        DownloadManager.getInstance().resume(downloadEntity, false)
                    }
                }

                else -> {
                    binding.root.setOnClickListener {
                        childEventHelper.trackCWRecentlyPlayedClick("游戏", downloadEntity)
                        ToastUtils.showToast(downloadEntity.status.toString())
                    }
                }
            }

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

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

        override fun provideExposureData(): ExposureEvent? {
            return boundedItem?.exposureEvent?.getFreshExposureEvent()
        }
    }
}