package com.base.pdfreaderallpdfreader.ui.main

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.pdfreaderallpdfreader.R
import com.base.pdfreaderallpdfreader.bean.DocumentBean
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_EXCEL
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_PDF
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_PPT
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_WORD
import com.base.pdfreaderallpdfreader.databinding.ItemDocumentBinding
import com.base.pdfreaderallpdfreader.utils.KotlinExt.toFormatSize
import com.base.pdfreaderallpdfreader.utils.KotlinExt.toFormatTime5
import com.base.pdfreaderallpdfreader.utils.LogEx
import com.base.pdfreaderallpdfreader.utils.XmlEx.inflate
import com.chad.library.adapter4.BaseQuickAdapter
import java.io.File

class DocumentAdapter : BaseQuickAdapter<DocumentBean, DocumentAdapter.DocumentViewHolder>() {

    private val TAG = "DocumentAdapter"

    inner class DocumentViewHolder(view: View) : ViewHolder(view)

    var moreAction: ((item: DocumentBean) -> Unit)? = null
    var itemClickAction: ((item: DocumentBean) -> Unit)? = null

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: DocumentViewHolder, position: Int, item: DocumentBean?) {
        item ?: return
        val binding = ItemDocumentBinding.bind(holder.itemView)

        when (item.type) {
            TYPE_PDF -> {
                LogEx.logDebug(TAG, "pdf state = ${item.state}")
                if (item.state == 0) {
                    binding.ivIcon.setImageResource(R.mipmap.r_pdf)
                } else {
                    binding.ivIcon.setImageResource(R.mipmap.rv_pdf_lock)
                }
            }

            TYPE_WORD -> {
                binding.ivIcon.setImageResource(R.mipmap.rv_word)
            }

            TYPE_EXCEL -> {
                binding.ivIcon.setImageResource(R.mipmap.rv_excel)
            }

            TYPE_PPT -> {
                binding.ivIcon.setImageResource(R.mipmap.r_ppt)
            }
        }
        val file = File(item.path)
        binding.tvName.text = file.name
        binding.tvInfo.text = file.lastModified().toFormatTime5() + "  " + file.length().toFormatSize()

        binding.flMore.setOnClickListener {
            moreAction?.invoke(item)
        }
        binding.root.setOnClickListener {
            itemClickAction?.invoke(item)
        }
    }

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