package org.mosad.teapod.util.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import org.mosad.teapod.R
import org.mosad.teapod.databinding.ItemMediaBinding
import org.mosad.teapod.util.ItemMedia

class MediaItemListAdapter(private val onClickListener: OnClickListener, private val itemOffset: Int = 0) : ListAdapter<ItemMedia, MediaItemListAdapter.MediaViewHolder>(DiffCallback) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MediaViewHolder {
        val binding = ItemMediaBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        binding.root.layoutParams.apply {
            width = (parent.measuredWidth / parent.context.resources.getInteger(R.integer.item_media_columns)) - itemOffset
        }

        return MediaViewHolder(binding)
    }

    override fun onBindViewHolder(holder: MediaViewHolder, position: Int) {
        val item = getItem(position)
        holder.binding.root.setOnClickListener {
            onClickListener.onClick(item)
        }
        holder.bind(item)
    }

    inner class MediaViewHolder(val binding: ItemMediaBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: ItemMedia) {
            binding.textTitle.text = item.title

            Glide.with(binding.root.context)
                .load(item.posterUrl)
                .into(binding.imagePoster)

            binding.imageEpisodePlay.isVisible = false
            binding.progressPlayhead.isVisible = false
        }
    }

    companion object DiffCallback : DiffUtil.ItemCallback<ItemMedia>() {
        override fun areItemsTheSame(oldItem: ItemMedia, newItem: ItemMedia): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: ItemMedia, newItem: ItemMedia): Boolean {
            return oldItem == newItem
        }
    }

    class OnClickListener(val clickListener: (item: ItemMedia) -> Unit) {
        fun onClick(item: ItemMedia) = clickListener(item)
    }
}