package com.design.wallpapergallery.adapter

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.design.wallpapergallery.R
import com.design.wallpapergallery.data.Photo
import com.design.wallpapergallery.listener.MainSecListener
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.request.RequestOptions
import com.design.wallpapergallery.databinding.ItemClassifyOpenBinding

class ClassifyOpenAdapter : RecyclerView.Adapter<ClassifyOpenAdapter.MainInViewHolder>() {
    private lateinit var context: Context
    private var coverList: List<Photo> = mutableListOf()
    private lateinit var listener: MainSecListener

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

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

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

    override fun onBindViewHolder(holder: MainInViewHolder, position: Int) {
        if(position==0){
            holder.binding.start.visibility = View.VISIBLE
        }else if(position==itemCount-1){
            holder.binding.end.visibility = View.VISIBLE
        }else{
            holder.binding.start.visibility = View.GONE
            holder.binding.end.visibility = View.GONE
        }
        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: MainSecListener) {
        this.listener = listener
    }

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