package com.gh.gamecenter.download

import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.core.graphics.drawable.toBitmap
import androidx.core.graphics.drawable.toDrawable
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.common.exposure.ExposureEvent
import com.gh.common.exposure.ExposureEvent.Companion.createEvent
import com.gh.common.exposure.ExposureSource
import com.gh.common.exposure.ExposureType
import com.gh.common.exposure.IExposable
import com.gh.common.simulator.SimulatorGameManager.isSimulatorGame
import com.gh.common.util.*
import com.gh.common.util.DownloadItemUtils.setOnClickListener
import com.gh.common.util.DownloadItemUtils.updateItem
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.utils.safelyGetInRelease
import com.gh.gamecenter.databinding.GameItemBinding
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.game.GameItemViewHolder
import com.gh.gamecenter.manager.PackagesManager.isInstalled
import com.lightgame.adapter.BaseRecyclerAdapter
import java.util.*

class NewInstalledGameFragmentAdapter(context: Context, private var mViewModel: InstalledGameViewModel) :
    BaseRecyclerAdapter<RecyclerView.ViewHolder>(context), IExposable {

    private var gameList = ArrayList<GameEntity>()

    private val mExposureSource by lazy {
        ArrayList<ExposureSource>().apply {
            add(ExposureSource("下载管理"))
            add(ExposureSource("已安装"))
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun submitList(dataList: ArrayList<GameEntity>) {
        gameList = dataList
        notifyDataSetChanged()
    }

    private fun initGameNormal(holder: GameItemViewHolder, gameEntity: GameEntity) {
        gameEntity.collection = ArrayList() // 清空集合,防止下载按钮会因为存在集合而清空合集包的状态判断
        holder.bindGameItem(gameEntity, isShowPlatform = true)
        holder.initServerType(gameEntity)
        val binding = holder.binding
        val name: String?
        if (gameEntity.getApk().size > 0) {
            name = String.format(
                "%s - %s", gameEntity.name,
                PlatformUtils.getInstance(binding.root.context)
                    .getPlatformName(gameEntity.getApk()[0].getPlatform())
            )
            var drawable = PackageUtils.getIconByPackageName(
                binding.root.context,
                gameEntity.getApk()[0].packageName
            )
            if (drawable != null && (drawable.intrinsicWidth >= 300 || drawable.intrinsicHeight >= 300)) {
                drawable = drawable.toBitmap(200, 200).toDrawable(mContext.resources)
            }
            binding.gameIconView.getIconIv().hierarchy.setPlaceholderImage(drawable)
            binding.gameIconView.getIconDecoratorIv().visibility = View.GONE
            if (isSimulatorGame(gameEntity)) {
                binding.gameDes.text = String.format("V%s", gameEntity.getApk()[0].version)
            } else {
                binding.gameDes.text = String.format(
                    "V%s", PackageUtils.getVersionNameByPackageName(
                        gameEntity.getApk()[0].packageName
                    )
                )
            }
        } else {
            name = gameEntity.name
            binding.gameIconView.displayGameIcon(
                gameEntity.getRawIconInAdvanced(),
                gameEntity.iconSubscript
            )
            binding.gameDes.text = gameEntity.brief
        }
        if (isSimulatorGame(gameEntity)) {
            binding.gameIconView.displayGameIcon(gameEntity.icon, gameEntity.iconSubscript)
        }
        binding.gameName.text = name
        generateExposureEvent(gameEntity)
        setOnClickListener(
            binding.root.context,
            binding.downloadBtn,
            gameEntity,
            1,
            this@NewInstalledGameFragmentAdapter,
            "(我的光环-已安装)", "我的光环-已安装" + ":" + gameEntity.name,
            gameEntity.exposureEvent //            , () -> MtaHelper.onEvent("下载管理", "已安装", binding.downloadBtn.getText().toString())
        )
        updateItem(binding.root.context, gameEntity, GameViewHolder(binding), !gameEntity.isPluggable)
        holder.itemView.setOnClickListener { v: View? ->
            DataCollectionUtils.uploadClick(binding.root.context, "列表", "我的光环-我的游戏", gameEntity.name)
            GameDetailActivity.startGameDetailActivity(
                binding.root.context,
                gameEntity.id,
                "(我的光环:我的游戏)",
                gameEntity.exposureEvent
            )
        }

        // 强制修改该列表安装状态（如果该包是合集且安装了合集内任意一个光环的游戏包都不显示插件化）
        val apkList = gameEntity.getApk()
        if (holder.binding.downloadBtn.text.toString().contains("化") && apkList.size == 1) {
            val (packageName) = apkList[0]
            val pluggableCollection = gameEntity.pluggableCollection
            if (pluggableCollection != null && pluggableCollection.packages.contains(packageName)) {
                for (pkg in pluggableCollection.packages) {
                    val ghId = PackageUtils.getGhId(pkg)
                    if (isInstalled(pkg) && ghId != null && gameEntity.id == ghId.toString()) {
                        holder.binding.downloadBtn.setText(R.string.launch)
                        holder.binding.downloadBtn.setBackgroundResource(R.drawable.download_button_normal_style)
                    }
                }
            }
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (gameList.size != 0 && position >= 0 && position < gameList.size) {
            ItemViewType.GAME_NORMAL
        } else ItemViewType.LOADING
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ItemViewType.GAME_NORMAL -> GameItemViewHolder(
                GameItemBinding.bind(mLayoutInflater.inflate(R.layout.game_item, parent, false))
            )
            else -> FooterViewHolder(
                mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false)
            )
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is GameItemViewHolder) {
            val gameEntity = gameList.safelyGetInRelease(position)
            if (gameEntity != null) {
                initGameNormal(holder, gameEntity)
            }
        }
    }

    override fun getItemCount(): Int {
        if (gameList.isEmpty() && !mViewModel.isRemove) {
            return 1
        }
        return if (mViewModel.isRemove) {
            gameList.size
        } else gameList.size + 1
    }

    private fun generateExposureEvent(gameEntity: GameEntity) {
        val event = createEvent(gameEntity, mExposureSource, null, ExposureType.EXPOSURE)
        gameEntity.exposureEvent = event
    }

    override fun getEventByPosition(pos: Int): ExposureEvent? = gameList[pos].exposureEvent

    override fun getEventListByPosition(pos: Int): List<ExposureEvent>? = null
}