package com.gh.gamecenter.gamedetail.fuli.kaifu

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.databinding.ItemGameServerTestTimeBinding
import com.gh.gamecenter.databinding.ItemServerCalendarServerBinding
import com.gh.gamecenter.databinding.ItemServersCalendarBinding
import com.gh.gamecenter.feature.game.GameItemViewHolder
import splitties.views.backgroundColor

class ServersCalendarListAdapter(
    context: Context,
    private val viewModel: ServersCalendarListViewModel
) : ListAdapter<ServersCalendarListViewModel.ItemData>(context) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return when (viewType) {
            ITEM_TYPE_FOOTER -> FooterViewHolder(mLayoutInflater.inflate(com.gh.gamecenter.common.R.layout.refresh_footerview, parent, false))
            ITEM_TYPE_DATA_ITEM -> ServersCalendarViewHolder(parent.toBinding())
            else -> ServersCalendarTimeViewHolder(parent.toBinding())
        }
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        when (holder) {
            is ServersCalendarViewHolder -> {
                val game = mEntityList[position].game ?: return

                holder.binding.root.backgroundColor = ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.ui_surface)

                holder.binding.icon.displayGameIcon(game.toGameEntity())
                holder.binding.gameName.text = game.name
                holder.binding.gameName.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_primary))

                // 副标题
                GameItemViewHolder.initGameSubtitleAndAdLabel(
                    game.toGameEntity(),
                    holder.binding.subtitle
                )

                // 如果开服表总数超过3个，显示开服表总数
                if (game.serversTotal > MAX_DISPLAY_SERVER_LIST_SIZE) {
                    holder.binding.serverCount.visibility = View.VISIBLE
                    holder.binding.serverCount.text =
                        holder.binding.root.context.getString(
                            R.string.servers_calendar_list_server_count,
                            game.serversTotal
                        )
                } else {
                    holder.binding.serverCount.visibility = View.GONE
                }

                // 最多显示3条开服列表数据
                val serverList = if (game.servers.size > MAX_DISPLAY_SERVER_LIST_SIZE) {
                    game.servers.subList(0, MAX_DISPLAY_SERVER_LIST_SIZE)
                } else {
                    game.servers
                }
                holder.binding.servers.removeAllViews()
                holder.binding.serversContainer.background = ContextCompat.getDrawable(
                    mContext,
                    R.drawable.bg_shape_f8_radius_8
                )
                serverList.forEachIndexed { index, server ->
                    ItemServerCalendarServerBinding.inflate(
                        mLayoutInflater,
                        holder.binding.servers,
                        true
                    ).apply {
                        // 优先展示服务器名字，若服务器名字为空则展示备注
                        val note = server.getNote()
                        val remark = server.remark
                        val name = if (note.isNullOrEmpty()) remark else note
                        this.name.text = name
                        this.time.text = server.getFormatTime("HH:mm")
                        root.layoutParams = (root.layoutParams as ViewGroup.MarginLayoutParams).apply {
                            bottomMargin = if (index < serverList.size - 1) 8F.dip2px() else 0
                        }
                    }
                }

                holder.binding.root.setOnClickListener {
                    DirectUtils.directToGameServerCalendar(
                        context = it.context,
                        gameId = game.id,
                        kaifuTime = game.startMidnight
                    )
                    NewLogUtils.logLaunchServerSubscribeClick(
                        gameId = game.id,
                        gameName = game.name,
                        launchServerTime = game.startMidnight.toInt()
                    )
                }
            }

            is ServersCalendarTimeViewHolder -> {
                holder.binding.root.backgroundColor = ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.ui_surface)
                holder.binding.timeTv.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_secondary))
                holder.binding.timeTv.text =
                    ServersCalendarListFragment.formatTime(mContext, (mEntityList[position].time ?: 0) * 1000)
            }

            is FooterViewHolder -> initFooterViewHolder(holder, mIsLoading, mIsNetworkError, mIsOver)
        }
    }

    fun initFooterViewHolder(
        viewHolder: FooterViewHolder,
        isLoading: Boolean,
        isNetworkError: Boolean,
        isOver: Boolean
    ) {
        viewHolder.run {
            if (isNetworkError) {
                loading.visibility = View.GONE
                hint.setText(com.gh.gamecenter.common.R.string.loading_failed_retry)
                itemView.isClickable = true
                itemView.setOnClickListener { viewModel.load(LoadType.RETRY) }
            } else if (isOver) {
                loading.visibility = View.GONE
                hint.setText(com.gh.gamecenter.common.R.string.load_over_hint)
                itemView.isClickable = false
                itemView.setOnClickListener(null)
            } else if (isLoading) {
                loading.visibility = View.VISIBLE
                hint.setText(com.gh.gamecenter.common.R.string.loading)
                itemView.isClickable = false
                itemView.setOnClickListener(null)
            } else {
                loading.visibility = View.GONE
                hint.setText(com.gh.gamecenter.common.R.string.loading_more_hint)
                itemView.isClickable = false
                itemView.setOnClickListener(null)
            }
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (mEntityList[position].footer) {
            ITEM_TYPE_FOOTER
        } else if(mEntityList[position].time != null) {
            ITEM_TYPE_DATE_HEADER
        } else {
            ITEM_TYPE_DATA_ITEM
        }
    }

    override fun getItemCount(): Int = mEntityList.size

    class ServersCalendarViewHolder(val binding: ItemServersCalendarBinding) : ViewHolder(binding.root)

    class ServersCalendarTimeViewHolder(var binding: ItemGameServerTestTimeBinding) : ViewHolder(binding.root)

    companion object {

        private const val ITEM_TYPE_FOOTER = 100

        private const val ITEM_TYPE_DATE_HEADER = 200

        private const val ITEM_TYPE_DATA_ITEM = 300

        private const val MAX_DISPLAY_SERVER_LIST_SIZE = 3
    }
}