package com.photo.keyboard.themes.adapter

import android.content.Context
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.photo.keyboard.themes.R
import com.photo.keyboard.themes.data.Parent
import com.photo.keyboard.themes.databinding.ItemMainBinding
import com.photo.keyboard.themes.listener.MainListener
import com.photo.keyboard.themes.manager.Utils

class MainAdapter(var con: Context, var data: List<Parent>) :
    RecyclerView.Adapter<MainAdapter.TabViewHolder>() {

    private var old = -4
    private var cur = 0

    private lateinit var mListener: MainListener

    inner class TabViewHolder(var viewbing: ItemMainBinding) :
        RecyclerView.ViewHolder(viewbing.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TabViewHolder {
        val inflate = ItemMainBinding.inflate(LayoutInflater.from(con), parent, false)

        return TabViewHolder(inflate)
    }

    fun setListener(listener: MainListener) {
        mListener = listener

    }

    fun updateCurPos(pos: Int) {
        old = cur
        cur = pos
        notifyItemChanged(old)
        notifyItemChanged(pos)

    }

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

    override fun onBindViewHolder(holder: TabViewHolder, position: Int) {
        data[position].run {
            holder.viewbing.classTile.apply {
                Utils.setFont(this)
                text = className
            }

            val ims = listOf<ImageView>(
                holder.viewbing.preview1,
                holder.viewbing.preview2,
                holder.viewbing.preview3,
                holder.viewbing.preview4
            )

            list?.forEachIndexed { index, infoChild ->
                val imageView = ims[index]
                Glide.with(con).load(infoChild.preview)
                    .transform(RoundedCorners(Utils.dpToUnitPx(10f)))
                    .placeholder(ContextCompat.getDrawable(con, R.mipmap.placholder))
                    .into(imageView)
                imageView.setOnClickListener {
                    mListener.onHomeClick(infoChild)
                }
            }
           holder.viewbing.btnMore.setOnClickListener {
               mListener.onHomeClickMore(this)
           }

        }
    }

    private fun setView(holder: TabViewHolder, boolean: Boolean) {

        holder.viewbing.classTile.let {
            it.isSelected = boolean
            if (boolean) {
                it.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18F)
            } else {
                it.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15F)
            }

        }
    }
}