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

import android.content.Context
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.databind.BindingAdapters
import com.gh.common.util.DataCollectionUtils
import com.gh.common.util.DialogUtils
import com.gh.common.util.DownloadItemUtils.setOnClickListener
import com.gh.common.util.DownloadItemUtils.updateItem
import com.gh.common.util.HomePluggableHelper
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.PluginLocation
import com.gh.gamecenter.feature.game.GameItemViewHolder.Companion.initGameSubtitleAndAdLabel
import com.gh.gamecenter.feature.utils.PlatformUtils
import com.gh.gamecenter.home.HomeDividerViewHolder
import com.gh.gamecenter.home.PluginDisplayStatus
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.eventlistener.OtherItemEventHelper
import com.gh.gamecenter.home.custom.viewholder.CustomGameItemViewHolder
import com.gh.gamecenter.home.custom.viewholder.CustomGamePluggableViewHolder
import com.lightgame.download.DownloadEntity
import com.lightgame.utils.Utils

/**
 * Created by khy on 15/08/17.
 *
 *
 * update on 27/12/19
 * link:https://gitlab.ghzs.com/pm/halo-app-issues/issues/730 (5)
 */
class CustomGamePluginAdapter(
    private val context: Context,
    private val viewModel: CustomPageViewModel,
    private val childEventHelper: OtherItemEventHelper,
    private val updateDisplayType: IUpdateDisplayType
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private var mPluginDisplayStatus = PluginDisplayStatus.CLOSE
    private var dataList: List<GameEntity> = listOf()

    fun setData(data: List<GameEntity>) {
        if (dataList != data) {
            dataList = data
            notifyDataSetChanged()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == ItemViewType.ITEM_BODY) {
            CustomGamePluggableViewHolder(parent.toBinding())
        } else {
            HomeDividerViewHolder(parent.toBinding())
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is CustomGamePluggableViewHolder) {
            initGameNormalViewHolder(holder, position)
        } else if (holder is HomeDividerViewHolder) {
            holder.bindView(8f)
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (mPluginDisplayStatus !== PluginDisplayStatus.OPEN) {
            ItemViewType.ITEM_BODY
        } else {
            if (position != itemCount - 1) {
                ItemViewType.ITEM_BODY
            } else {
                ItemViewType.DIVIDER_ITEM
            }
        }
    }

    private fun initGameNormalViewHolder(holder: CustomGamePluggableViewHolder, position: Int) {
        val binding = holder.binding
        val gameEntity = dataList[position]

        holder.initServerType(gameEntity)
        binding.gameIconView.displayGameIcon(gameEntity)
        binding.gameRating.textSize =
            (if (gameEntity.commentCount > 3) 12 else 10).toFloat()
        BindingAdapters.setGameName(binding.gameName, gameEntity, true)
        binding.gamePlayCount.visibility = View.GONE
        BindingAdapters.setGameTagsWithSellingPoint(binding.labelList, binding.layoutSellingPoints, gameEntity, "")
        binding.gameRating.setDrawableStart(
            if (gameEntity.commentCount > 3) com.gh.gamecenter.feature.R.drawable.game_horizontal_rating.toDrawable() else null,
            null,
            null
        )
        binding.gameRating.setPadding(
            0,
            0,
            if (gameEntity.commentCount > 3) DisplayUtils.dip2px(8F) else 0,
            0
        )
        binding.gameRating.text =
            if (gameEntity.commentCount > 3) (if (gameEntity.star.toDouble() == 10.0) "10" else gameEntity.star.toString()) else ""
        binding.gameRating.setTextColor(if (gameEntity.commentCount > 3) com.gh.gamecenter.common.R.color.text_theme.toColor() else com.gh.gamecenter.common.R.color.primary_theme.toColor())
        binding.gameDes.text = gameEntity.decoratedDes
        binding.recommendStar.rating = gameEntity.recommendStar.toFloat()
        initGameSubtitleAndAdLabel(
            gameEntity,
            binding.gameSubtitleTv,
            binding.gameNameContainer,
            binding.gameName,
            false,
            null,
            false,
            null
        )
        holder.itemView.setOnClickListener { v: View? ->
            DataCollectionUtils.uploadClick(
                context,
                "插件化" + "-列表",
                "游戏-专题",
                gameEntity.name
            )
            childEventHelper.trackPluginAreaClick("游戏", gameEntity)
            childEventHelper.navigateToGameDetailPageByGame(1, gameEntity)
        }

        setOnClickListener(
            context,
            binding.downloadBtn,
            gameEntity,
            1,
            this@CustomGamePluginAdapter,
            StringUtils.buildString("(游戏-专题:", "插件化", "-列表[", 1.toString(), "])"),
            location = StringUtils.buildString("游戏-专题-", "插件化", ":", gameEntity.name),
            traceEvent = gameEntity.exposureEvent,
        ) {
            childEventHelper.trackPluginAreaClick("按钮", gameEntity)
            childEventHelper.onDownloadButtonClick(1, gameEntity)
        }
        updateItem(
            context,
            gameEntity,
            CustomGameItemViewHolder.CustomGameViewHolder(holder.binding),
            PluginLocation.only_index,
            false,
            null
        )
        holder.binding.layoutTitle.root.goneIf(true)
        holder.binding.neverRemind.goneIf(false)
        holder.binding.neverRemind.setOnClickListener { v: View? ->
            DialogUtils.showPluggableNeverRemindDialog(
                context, String.format(
                    "%s - %s",
                    gameEntity.name,
                    PlatformUtils.getInstance(context).getPlatformName(
                        gameEntity.getApk()[0].getPlatform()
                    )
                )
            ) {
                Utils.toast(context, "不再提醒设置成功")
                HomePluggableHelper.setHomePluggableFilterData(gameEntity, true)

                viewModel.temporarilyBlockGameInPluginItem(gameId = gameEntity.id)

                updateDisplayType.update(PluginDisplayStatus.DEFAULT)
            }
        }
        val layoutParams = holder.binding.downloadBtn.layoutParams
        if (layoutParams is LinearLayout.LayoutParams) {
            layoutParams.gravity = Gravity.TOP
            layoutParams.topMargin = DisplayUtils.dip2px(4f)
        }
        HomePluggableHelper.setHomePluggableFilterData(gameEntity, false)
    }

    override fun getItemCount(): Int {
        return if (mPluginDisplayStatus === PluginDisplayStatus.OPEN) {
            dataList.size + 1 // 显示底部线条
        } else if (mPluginDisplayStatus === PluginDisplayStatus.OPEN_AND_BUTTON) {
            dataList.size
        } else if (mPluginDisplayStatus === PluginDisplayStatus.OPEN_TWO_AND_BUTTON) {
            if (dataList.size > 2) 2 else dataList.size
        } else {
            0
        }
    }

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

    fun openList(pluginDisplayStatus: PluginDisplayStatus) {
        if (mPluginDisplayStatus !== pluginDisplayStatus) {
            mPluginDisplayStatus = pluginDisplayStatus
            notifyDataSetChanged()
        } else {
            notifyItemRangeChanged(0, itemCount)
        }
    }

    interface IUpdateDisplayType {
        fun update(status: PluginDisplayStatus)
    }
}