package com.base.browserwhite.ui.activity.bookmark

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.base.browserwhite.R
import com.base.browserwhite.bean.BookmarkBean
import com.base.browserwhite.databinding.ItemBookmarkBinding
import com.base.browserwhite.utils.XmlEx.inflate
import com.chad.library.adapter4.BaseQuickAdapter
import java.util.Random


class BookmarkAdapter : BaseQuickAdapter<BookmarkBean, BookmarkAdapter.BookmarkHolder>() {

    var currentFolder = BookmarkBean.folderRoot
    var changeFolderAction: ((folder: String) -> Unit)? = null

    inner class BookmarkHolder(view: View) : ViewHolder(view)

    override fun onBindViewHolder(holder: BookmarkHolder, position: Int, item: BookmarkBean?) {
        if (item == null) {
            return
        }

        val binding = ItemBookmarkBinding.bind(holder.itemView)
        val context = holder.itemView.context
        binding.tvName.text = item.name
        if (!item.isFolder) {
            binding.card.radius = context.resources.getDimension(R.dimen.dp_5)
            binding.iv.visibility = View.GONE
            binding.tvLetters.visibility = View.VISIBLE
            binding.tvLetters.background = getRandomColorDrawable()
            binding.tvLetters.text = item.name.first().toString()
        } else {
            binding.card.radius = 0f
            binding.tvLetters.visibility = View.GONE
            binding.iv.visibility = View.VISIBLE
            binding.iv.setImageResource(R.mipmap.wenjiajia_bookmark)
        }

        binding.root.setOnClickListener {
            if (!item.isFolder) return@setOnClickListener
            currentFolder = item.name
            changeFolderAction?.invoke(currentFolder)
        }

    }

    override fun getItemViewType(position: Int, list: List<BookmarkBean>): Int {
        return list[position].viewType

    }

    override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): BookmarkHolder {

        val layout = when (viewType) {
            0 -> R.layout.item_bookmark
            else -> R.layout.item_bookmark
        }
        return BookmarkHolder(layout.inflate(parent))
    }

    fun getRandomColorDrawable(): ColorDrawable {
        val random = Random()
        val red: Int = random.nextInt(256)
        val green: Int = random.nextInt(256)
        val blue: Int = random.nextInt(256)
        val color = Color.rgb(red, green, blue)
        return ColorDrawable(color)
    }

    fun canBeforeFolder(): Boolean {
        return currentFolder != BookmarkBean.folderRoot
    }

    fun beforeFolder() {
        currentFolder = BookmarkBean.folderRoot
        changeFolderAction?.invoke(currentFolder)
    }
}