package com.demoscene.tv.ui

import android.graphics.drawable.Drawable
import android.view.ViewGroup
import androidx.leanback.widget.ImageCardView
import androidx.leanback.widget.Presenter
import com.bumptech.glide.Glide
import com.demoscene.tv.model.Demo
import kotlin.properties.Delegates

/**
 * Presenter for demo cards in the browse rows
 */
class CardPresenter : Presenter() {
    
    private var mDefaultCardImage: Drawable? = null
    private var sSelectedBackgroundColor: Int by Delegates.notNull()
    private var sDefaultBackgroundColor: Int by Delegates.notNull()

    override fun onCreateViewHolder(parent: ViewGroup): ViewHolder {
        sDefaultBackgroundColor = parent.context.getColor(android.R.color.transparent)
        sSelectedBackgroundColor = parent.context.getColor(android.R.color.holo_blue_dark)

        val cardView = object : ImageCardView(parent.context) {
            override fun setSelected(selected: Boolean) {
                updateCardBackgroundColor(this, selected)
                super.setSelected(selected)
            }
        }

        cardView.isFocusable = true
        cardView.isFocusableInTouchMode = true
        updateCardBackgroundColor(cardView, false)
        return ViewHolder(cardView)
    }

    override fun onBindViewHolder(viewHolder: ViewHolder, item: Any) {
        val demo = item as Demo
        val cardView = viewHolder.view as ImageCardView

        cardView.titleText = demo.title
        cardView.contentText = "${demo.group} (${demo.year})"
        cardView.setMainImageDimensions(CARD_WIDTH, CARD_HEIGHT)

        // Load thumbnail with Glide
        Glide.with(viewHolder.view.context)
            .load(demo.thumbnailUrl)
            .centerCrop()
            .error(mDefaultCardImage)
            .into(cardView.mainImageView)
    }

    override fun onUnbindViewHolder(viewHolder: ViewHolder) {
        val cardView = viewHolder.view as ImageCardView
        cardView.badgeImage = null
        cardView.mainImage = null
    }

    private fun updateCardBackgroundColor(view: ImageCardView, selected: Boolean) {
        val color = if (selected) sSelectedBackgroundColor else sDefaultBackgroundColor
        view.setBackgroundColor(color)
        view.setInfoAreaBackgroundColor(color)
    }

    companion object {
        private const val CARD_WIDTH = 313
        private const val CARD_HEIGHT = 176
    }
}
