package com.drawing.drawsketch.main

import android.content.Context
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.drawing.drawsketch.App
import com.drawing.drawsketch.BaseAdapter
import com.drawing.drawsketch.Utils
import com.drawing.drawsketch.databinding.MainAdapterBinding
import java.io.IOException
import kotlin.math.min

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

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


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

        data[position].let {

            val listAssetFiles = Utils.listAssetFiles(mContext, it)




            Utils.loadImage(
                mContext,
                it + "/" + listAssetFiles[0],
                image = itemHolder.vb.mainImage
            )
            val replace = Utils.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
    }
}