package com.apps.pixwall.adapter

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.apps.pixwall.R
import com.apps.pixwall.data.Paper
import com.apps.pixwall.databinding.ItemInBinding
import com.apps.pixwall.listener.MainInListener
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.request.RequestOptions

class MainInAdapter : RecyclerView.Adapter<MainInAdapter.MainInViewHolder>() {
    private lateinit var context: Context
    private var coverList: List<Paper> = mutableListOf()
    private lateinit var listener: MainInListener

    class MainInViewHolder(val binding: ItemInBinding) : RecyclerView.ViewHolder(binding.root)

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

    override fun getItemCount(): Int {
        return coverList.size
    }

    override fun onBindViewHolder(holder: MainInViewHolder, position: Int) {
        val previewUrl400 = coverList[position].previewUrl400
        val previewUrl200 = coverList[position].previewUrl200
        Log.d("MainInAdapter", "previewUrl400 is $previewUrl400 previewUrl200 is $previewUrl200")
        Glide.with(context).load(previewUrl400).placeholder(R.mipmap.bg_placeholder)
            .error(R.mipmap.bg_placeholder).thumbnail(
                Glide.with(context)
                    .asDrawable()
                    .load(previewUrl200)
                    .apply(
                        RequestOptions()
                            .format(DecodeFormat.PREFER_RGB_565)
                    )
                    .placeholder(R.mipmap.bg_placeholder)
                    .centerCrop()
            ).into(holder.binding.inImage)
        holder.binding.inImage.setOnClickListener {
            listener.inItemClick(coverList[position])
        }
    }

    fun setListener(listener: MainInListener) {
        this.listener = listener
    }

    fun setCoverList(list: List<Paper>) {
        this.coverList = list
    }
}