package com.sketch.ar.artdrawing.main

import android.content.Context
import android.graphics.BitmapFactory
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.net.toUri
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import com.sketch.ar.artdrawing.databinding.AdapterMainCategoryBinding
import com.sketch.ar.artdrawing.utils.BaseAdapter
import com.sketch.ar.artdrawing.utils.CommonUtils
import java.io.IOException
import kotlin.math.min

class MainCategoryAdapter(context: Context, var clickAction: (categoryName: String) -> Unit) :
    BaseAdapter<String, AdapterMainCategoryBinding>(context) {
    override fun getViewBinding(parent: ViewGroup?): AdapterMainCategoryBinding {

        return AdapterMainCategoryBinding.inflate(
            LayoutInflater.from(parent?.context),
            parent,
            false
        )
    }


    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val itemHolder = holder as VHolder<AdapterMainCategoryBinding>

        data[position].let {

            val listAssetFiles = CommonUtils.listAssetFiles(mContext, it)
            val path = it + "/" + listAssetFiles[0]
            val uri = "file:///android_asset/$path".toUri()
            itemHolder.vb.mainImage.let {
                Glide.with(mContext)
                    .asBitmap()
                    .load(uri)
                    .override(Target.SIZE_ORIGINAL)
                    .into(it)
            }

            val replace = CommonUtils.getDisPlayName(it)
            itemHolder.vb.mainCategoryName.text = replace
            itemHolder.vb.mainImage.setOnClickListener { view ->
                clickAction(it)
            }

        }

    }



    private fun getFirstFourFilesFromAssetsDir(context: Context, dirName: String): List<String> {
        val fileList: MutableList<String> = ArrayList()
        try {
            val assetManager = context.assets
            val files = assetManager.list(dirName)

            if (files != null) {
                val limit = min(4.0, files.size.toDouble()).toInt()
                for (i in 0..<limit) {
                    // 如果你需要完整路径可以写 dirName + "/" + files[i]
                    fileList.add(dirName + "/" + files[i])
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return fileList
    }
}