package com.offline.music.task.player.ui.adapter

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.offline.music.task.player.ProApp
import com.offline.music.task.player.R
import com.offline.music.task.player.databinding.SoundsOfAppliancesLayoutBinding
import com.offline.music.task.player.db.bean.Audio
import com.offline.music.task.player.tools.util.convertMillisToMinutesAndSecondsString
import com.offline.music.task.player.tools.util.getAudioDurationFromAssets
import com.offline.music.task.player.ui.activity.PlayerActivity

class HomeWhiteNoiseAdapter(
    private val context: Context,
    private val pdfList: List<Audio>,
) :
    RecyclerView.Adapter<HomeWhiteNoiseAdapter.PDFViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PDFViewHolder {
        val binding =
            SoundsOfAppliancesLayoutBinding.inflate(LayoutInflater.from(context), parent, false)
        return PDFViewHolder(binding)
    }

    override fun onBindViewHolder(holder: PDFViewHolder, position: Int) {
        val audio = pdfList[position]
        Glide.with(context)
            .load("file:///android_asset/${audio.image}")
            .into(holder.binding.image)
        holder.binding.name.text = audio.name
        val s = getAudioDurationFromAssets(context, audio.file)
        holder.binding.desc.text = convertMillisToMinutesAndSecondsString(s)

        if (ProApp.currentPlayingAudio != null) {
            if (ProApp.currentPlayingAudio?.file == audio.file) {
                holder.binding.playingLayout.visibility = View.VISIBLE
                holder.binding.name.setTextColor(context.getColor(R.color.blue))
                holder.binding.desc.setTextColor(context.getColor(R.color.blue))
            } else {
                holder.binding.playingLayout.visibility = View.GONE
                holder.binding.name.setTextColor(context.getColor(R.color.white))
                holder.binding.desc.setTextColor(context.getColor(R.color.white_60))
            }
        }
        holder.itemView.setOnClickListener {
            val intent = Intent(context, PlayerActivity::class.java);
            intent.putExtra(PlayerActivity.KEY_DETAILS_AUDIO, audio)
            context.startActivity(intent)
        }
    }

    override fun getItemCount(): Int = pdfList.size

    inner class PDFViewHolder(val binding: SoundsOfAppliancesLayoutBinding) :
        RecyclerView.ViewHolder(binding.root)

    private var itemClickListener: OnItemClickListener? = null

    fun setOnItemClickListener(listener: OnItemClickListener) {
        itemClickListener = listener
    }

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }
}