package com.gh.gamecenter.video.poster.photo

import android.database.Cursor
import android.net.Uri
import android.view.LayoutInflater
import android.view.ViewGroup
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.PhotoPosterItemBinding
import com.halo.assistant.HaloApp
import com.zhihu.matisse.internal.entity.Item
import com.zhihu.matisse.internal.entity.SelectionSpec
import com.zhihu.matisse.internal.ui.adapter.RecyclerViewCursorAdapter
import com.zhihu.matisse.internal.utils.PathUtils

class PhotoPosterAdapter : RecyclerViewCursorAdapter<PhotoPosterItemViewHolder>(null) {
    private val mCheckMap = HashMap<Int, Uri?>()

    private val mImageResize = HaloApp.getInstance().application.resources.displayMetrics.widthPixels / 3

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoPosterItemViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.photo_poster_item, parent, false)
        return PhotoPosterItemViewHolder(PhotoPosterItemBinding.bind(view))
    }

    override fun onBindViewHolder(holder: PhotoPosterItemViewHolder, cursor: Cursor?, position: Int) {
        if (mCheckMap[position] == null) mCheckMap[position] = null

        val item = Item.valueOf(cursor)
        SelectionSpec.getInstance().imageEngine.loadThumbnail(
            HaloApp.getInstance().application, mImageResize, null,
            holder.binding.preview, item.contentUri
        )
        holder.binding.checkView.isChecked = mCheckMap[position] != null
        holder.binding.checkView.isClickable = false
        holder.itemView.setOnClickListener {
            holder.binding.checkView.isChecked = !holder.binding.checkView.isChecked
            mCheckMap[position] = if (holder.binding.checkView.isChecked) item.contentUri else null
            for (entry in mCheckMap) {
                if (entry.value != null && entry.key != position) {
                    mCheckMap[entry.key] = null
                    notifyItemChanged(entry.key)
                }
            }
        }
    }

    override fun getItemViewType(position: Int, cursor: Cursor?): Int {
        return 0
    }

    fun getSelectImagePath(): String? {
        for (entry in mCheckMap) {
            if (entry.value != null) return PathUtils.getPath(HaloApp.getInstance().application, entry.value)
        }
        return null
    }
}

class PhotoPosterItemViewHolder(val binding: PhotoPosterItemBinding) : BaseRecyclerViewHolder<Any>(binding.root)
