package com.base.pdfviewerscannerwhite.ui.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.bean.DocumentBean
import com.base.pdfviewerscannerwhite.bean.DocumentBean.Companion.TYPE_PDF
import com.base.pdfviewerscannerwhite.databinding.ItemDocmentBinding
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatSize
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatTime
import com.base.pdfviewerscannerwhite.utils.XmlEx.inflate
import com.chad.library.adapter4.BaseQuickAdapter
import java.io.File

class DocumentAdapter : BaseQuickAdapter<DocumentBean, DocumentAdapter.DocumentViewHolder>() {
    inner class DocumentViewHolder(view: View) : ViewHolder(view)


    var itemClick: ((item: DocumentBean) -> Unit)? = null
    var bookmarkAction: ((addRemove: Boolean, path: String) -> Unit)? = null
    var moreAction: ((item: DocumentBean) -> Unit)? = null

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: DocumentViewHolder, position: Int, item: DocumentBean?) {
        if (item == null) return
        val binding = ItemDocmentBinding.bind(holder.itemView)
        if (item.type == TYPE_PDF) {
            binding.iv.setImageResource(R.mipmap.h_pdfiocn)
        }
        val file = File(item.path)
        binding.tvName.text = file.name
        binding.tvInfo.text = file.lastModified().toFormatTime() + " " + file.length().toFormatSize()
        if (item.isBookmarked) {
            binding.ivBookmark.setImageResource(R.mipmap.h_soucang_s)
        } else {
            binding.ivBookmark.setImageResource(R.mipmap.h_soucang_n)
        }

        binding.flBookmark.setOnClickListener {
            if (item.isBookmarked) {
                bookmarkAction?.invoke(false, item.path)
            } else {
                bookmarkAction?.invoke(true, item.path)
            }
            item.isBookmarked = !item.isBookmarked
            notifyItemChanged(position, "aaaa")
        }
        binding.flMore.setOnClickListener {
            moreAction?.invoke(item)
        }
        binding.root.setOnClickListener {
            itemClick?.invoke(item)
        }
    }

    override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): DocumentViewHolder {
        return DocumentViewHolder(R.layout.item_docment.inflate(parent))
    }
}