package org.mosad.teapod.util.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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.parser.crunchyroll.UpNextAccountItem

class MediaEpisodeListAdapter(private val onClickListener: OnClickListener, private val itemOffset: Int = 0) : ListAdapter<UpNextAccountItem, MediaEpisodeListAdapter.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: UpNextAccountItem) {
            val metadata = item.panel.episodeMetadata

            binding.textTitle.text = binding.root.context.getString(R.string.season_episode_title,
                metadata.seasonNumber, metadata.episodeNumber, metadata.seriesTitle
            )

            Glide.with(binding.imagePoster)
                .load(item.panel.images.thumbnail[0][0].source)
                .into(binding.imagePoster)

            // add watched progress
            val playheadProgress = ((item.playhead.toFloat() / (metadata.durationMs / 1000)) * 100)
                .toInt()
            binding.progressPlayhead.setProgressCompat(playheadProgress, false)
            binding.progressPlayhead.visibility = if (playheadProgress <= 0)
                View.GONE else View.VISIBLE
        }
    }

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

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

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