package com.xm.test.myfilemaster.adapter

import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.util.SparseBooleanArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.CheckBox
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.cloud.cleanjunksdk.similar.PicInfo
import com.xm.test.myfilemaster.R
import com.xm.test.myfilemaster.activity.SimilarImagesActivity
import com.xm.test.myfilemaster.util.FileUtil

class SimilarGridAdapter(
    list: MutableList<PicInfo>, context: Context,
    mStateCheckedMap: SparseBooleanArray, mPosition: Int): BaseAdapter(){

    private var context: Context
    private var dataList: MutableList<PicInfo>
    private var stateCheckedMap: SparseBooleanArray
    private var inflater: LayoutInflater
    private var mPosition: Int
    init {
        this.context = context
        this.dataList = list
        this.stateCheckedMap = mStateCheckedMap
        this.inflater = LayoutInflater.from(context)
        this.mPosition = mPosition
    }

    override fun getCount(): Int {
        return dataList.size
    }

    override fun getItem(position: Int): Any {
        return dataList[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var view = convertView
        val itemHolder: ViewHolder
        if (convertView != null){
            itemHolder = view?.tag as ViewHolder
        }else{
            view = inflater.inflate(R.layout.item_layout, null)
            itemHolder = ViewHolder()
            itemHolder.imageView = view.findViewById(R.id.item_image)
            itemHolder.checkBox = view.findViewById(R.id.check_item_image_switch)
            view.tag = itemHolder
        }
//            BitmapDrawable(context.resources, BitmapFactory.decodeFile(dataList[position].filePath))
        itemHolder.checkBox.visibility = if (SimilarImagesActivity.isClickEditBtn) View.VISIBLE else View.GONE
        Glide.with(context).load(dataList[position].path).centerCrop().into(itemHolder.imageView)
//        itemHolder.imageView.setImageDrawable(BitmapDrawable(context.resources, BitmapFactory.decodeFile(dataList[position].path)))
        itemHolder.imageView.layoutParams.height = FileUtil.dpToPx(83, context)

//            if (DuplicateImagesActivity.isClickCheckBoxAllBtn){
//                itemHolder.checkBox.isChecked = true
//            }else{
        itemHolder.checkBox.isChecked = stateCheckedMap[position]
//            }

        return view!!

    }

    fun setData(datas: MutableList<PicInfo>){
        this.dataList = datas
    }

    class ViewHolder{
        lateinit var checkBox: CheckBox
        lateinit var imageView: ImageView
    }
}