package com.base.browserwhite.ui.adapter

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.base.browserwhite.R
import com.base.browserwhite.bean.WebSiteBean
import com.base.browserwhite.bean.WebSiteBean.Companion.getLocalImage
import com.base.browserwhite.bean.defaultValue
import com.base.browserwhite.databinding.ItemWebsiteGrid2Binding
import com.base.browserwhite.databinding.ItemWebsiteGridBinding
import com.base.browserwhite.utils.AppPreferences
import com.base.browserwhite.utils.LogEx
import com.base.browserwhite.utils.XmlEx.inflate
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target

class WebsiteAdapter(val uiType: Int = 0, val click: (bean: WebSiteBean) -> Unit) :
    RecyclerView.Adapter<WebsiteAdapter.WebSiteViewHolder>() {

    private val TAG = "WebsiteAdapter"

    private val beanList = arrayListOf<WebSiteBean>()

    inner class WebSiteViewHolder(view: View) : ViewHolder(view) {
        var canDrag = true
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WebSiteViewHolder {
        val layout = if (uiType == 0) {
            R.layout.item_website_grid
        } else {
            R.layout.item_website_grid_2
        }
        return WebSiteViewHolder(layout.inflate(parent))
    }

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

    override fun onBindViewHolder(holder: WebSiteViewHolder, position: Int) {
        val bean = beanList[position]
        val context = holder.itemView.context
        when (uiType) {
            0 -> {
                val binding = ItemWebsiteGridBinding.bind(holder.itemView)
                if (bean.name == "Increase") {
                    binding.ivAdd.visibility = View.VISIBLE
                    binding.ivIcon.visibility = View.GONE
                    binding.ivAdd.setImageResource(bean.localIcon)
                } else {
                    binding.ivIcon.visibility = View.VISIBLE
                    binding.ivAdd.visibility = View.GONE
                    val bordIconName = arrayOf("Ebay", "Bing")
                    if (bordIconName.contains(bean.name)) {
                        binding.ivIcon.borderColor = ContextCompat.getColor(context, R.color.color_cbcdd7)
                        binding.ivIcon.borderWidth = 1
                    }
                    Glide.with(context).load(bean.icon_url).addListener(object : RequestListener<Drawable> {
                        override fun onLoadFailed(
                            e: GlideException?,
                            model: Any?,
                            target: Target<Drawable>,
                            isFirstResource: Boolean
                        ): Boolean {
                            // 返回 false 以允许 Glide 显示错误占位图
                            return false
                        }

                        override fun onResourceReady(
                            resource: Drawable,
                            model: Any,
                            target: Target<Drawable>?,
                            dataSource: DataSource,
                            isFirstResource: Boolean
                        ): Boolean {

                            // 返回 false 以允许 Glide 正常处理加载成功的图片
                            return false
                        }

                    }).error(bean.getLocalImage()).into(binding.ivIcon)
                }
                binding.tvName.text = bean.name
                holder.canDrag = !bean.increase
                binding.root.setOnClickListener {
                    click.invoke(bean)
                }
            }

            else -> {
                val binding = ItemWebsiteGrid2Binding.bind(holder.itemView)
                Glide.with(context).load(bean.icon_url).addListener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Drawable>,
                        isFirstResource: Boolean
                    ): Boolean {
                        // 返回 false 以允许 Glide 显示错误占位图
                        return false
                    }

                    override fun onResourceReady(
                        resource: Drawable,
                        model: Any,
                        target: Target<Drawable>?,
                        dataSource: DataSource,
                        isFirstResource: Boolean
                    ): Boolean {

                        // 返回 false 以允许 Glide 正常处理加载成功的图片
                        return false
                    }

                }).error(bean.getLocalImage()).into(binding.iv)
                binding.tvName.text = bean.name

                val isAdd = AppPreferences.getInstance().getBoolean("${bean.id}_${bean.name}", defaultValue(bean.name))
                if (isAdd) {
                    binding.ivSelectAdd.setImageResource(R.mipmap.w_xuan)
                } else {
                    binding.ivSelectAdd.setImageResource(R.mipmap.w_tianjia)
                }
                bean.isAdd = isAdd
                binding.ivSelectAdd.setOnClickListener {
                    AppPreferences.getInstance().putBoolean("${bean.id}_${bean.name}", !bean.isAdd)
                    notifyItemChanged(position)
                }
                binding.root.setOnClickListener {
                    click.invoke(bean)
                }
            }
        }

    }

    @SuppressLint("NotifyDataSetChanged")
    fun setData(webSiteList: List<WebSiteBean>?) {
        if (webSiteList.isNullOrEmpty()) return
        beanList.clear()
        beanList.addAll(webSiteList)
        notifyDataSetChanged()
    }

    fun changeBeanPosition(oldPosition: Int, newPosition: Int) {
        LogEx.logDebug(TAG, "oldPosition=$oldPosition newPosition=$newPosition")

        val bean = beanList[oldPosition]
        beanList.remove(bean)
        beanList.add(newPosition, bean)
    }
}