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.toBinding
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.databinding.ItemServersCalendarRemindBinding
import com.gh.gamecenter.feature.game.GameItemViewHolder
import java.text.SimpleDateFormat
import java.util.*

class ServersCalendarRemindListAdapter(
    context: Context,
    private val viewModel: ServersCalendarRemindListViewModel
) : ListAdapter<ServersCalendarRemindListViewModel.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))
            else -> ServersCalendarRemindViewHolder(parent.toBinding())
        }
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        if (holder is ServersCalendarRemindViewHolder) {
            val game = mEntityList[position].game ?: return

            holder.binding.icon.displayGameIcon(game.toGameEntity())
            holder.binding.gameName.text = game.name

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

            val context = holder.binding.root.context

            // 已知服: 展示设置开服时间+服务器名字/备注
            // 未知服: 展示关注开服日期
            val server = game.servers.firstOrNull() ?: return
            val notifySetting = server.notifySetting ?: return
            // 提醒状态
            val notifyStatus = game.notifyStatus ?: return
            if ((server.getNote()
                    .isNullOrEmpty() && server.remark.isEmpty()) || notifyStatus == NOTIFY_STATUS_HAS_NEW || notifyStatus == NOTIFY_STATUS_EXPIRED
            ) {// 未知服或未知服相关状态，仅展示日期
                val format = SimpleDateFormat("MM月dd日", Locale.getDefault())
                holder.binding.time.text = format.format(notifySetting.notifyTime * 1000)
            } else {// 已知服
                val format = SimpleDateFormat("MM月dd日 HH:mm", Locale.getDefault())
                // 优先展示服务器名字，若服务器名字为空则展示备注
                val note = server.getNote()
                val remark = server.remark
                val name = if (note.isNullOrEmpty()) remark else note
                holder.binding.time.text = context.getString(
                    R.string.servers_calendar_remind_list_server_name,
                    format.format(notifySetting.notifyTime * 1000),
                    name
                )
            }

            // 设置提醒状态文字颜色
            val statusTextColorId = if (notifyStatus == NOTIFY_STATUS_TODO || notifyStatus == NOTIFY_STATUS_COMING) {
                com.gh.gamecenter.common.R.color.text_theme
            } else {
                com.gh.gamecenter.common.R.color.text_tertiary
            }
            holder.binding.status.setTextColor(ContextCompat.getColor(context, statusTextColorId))

            // 设置提醒状态文案
            val statusTextId = when (notifyStatus) {
                NOTIFY_STATUS_TODO -> R.string.servers_calendar_remind_status_todo
                NOTIFY_STATUS_COMING -> R.string.servers_calendar_remind_status_coming
                NOTIFY_STATUS_OPENED -> R.string.servers_calendar_remind_status_opened
                NOTIFY_STATUS_HAS_NEW -> R.string.servers_calendar_remind_status_has_new
                else -> R.string.servers_calendar_remind_status_expired
            }
            holder.binding.status.text = context.getString(statusTextId)

            holder.binding.root.setOnClickListener {
                DirectUtils.directToGameServerCalendar(
                    context = it.context,
                    gameId = game.id,
                    kaifuTime = server.getTime()
                )
                NewLogUtils.logLaunchServerReminderClick(
                    gameId = game.id,
                    gameName = game.name,
                    reminderTime = (notifySetting.notifyTime - notifySetting.secondsAdvance).toInt(),
                    status = notifyStatus
                )
            }

        } else if (holder 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 {
            ITEM_TYPE_DATA
        }
    }

    override fun getItemCount(): Int = mEntityList.size

    class ServersCalendarRemindViewHolder(val binding: ItemServersCalendarRemindBinding) : ViewHolder(binding.root)

    companion object {

        /**
         * 待提醒
         */
        private const val NOTIFY_STATUS_TODO = "todo"

        /**
         * 即将开服
         */
        private const val NOTIFY_STATUS_COMING = "coming"

        /**
         * 已开服
         */
        private const val NOTIFY_STATUS_OPENED = "opened"

        /**
         * 有新服
         */
        private const val NOTIFY_STATUS_HAS_NEW = "has_new"

        /**
         * 已过期
         */
        private const val NOTIFY_STATUS_EXPIRED = "expired"

        /**
         * 未知服
         */
        private const val SERVER_TYPE_UNKNOWN = "未知服"

        private const val ITEM_TYPE_FOOTER = 100
        private const val ITEM_TYPE_DATA = 200
    }
}