package com.base.easyfilemanager.adapter

import android.annotation.SuppressLint
import android.os.Environment
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.base.easyfilemanager.R
import com.base.easyfilemanager.bean.FileBean
import com.base.easyfilemanager.bean.FileBean.Companion.isApk
import com.base.easyfilemanager.bean.FileBean.Companion.isAudio
import com.base.easyfilemanager.bean.FileBean.Companion.isDir
import com.base.easyfilemanager.bean.FileBean.Companion.isDocument
import com.base.easyfilemanager.bean.FileBean.Companion.isImage
import com.base.easyfilemanager.bean.FileBean.Companion.isVideo
import com.base.easyfilemanager.bean.FileBean.Companion.isZip
import com.base.easyfilemanager.databinding.ItemFileManagerListBinding
import com.base.easyfilemanager.helps.KotlinExt.toFormatSize
import com.base.easyfilemanager.view.XmlEx.inflate
import com.bumptech.glide.Glide
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale

@SuppressLint("NotifyDataSetChanged")
class FileManagerAdapter(
    private val allSelect: (select: Boolean) -> Unit,
    private val showEmpty: ((isShow: Boolean) -> Unit)? = null
) : RecyclerView.Adapter<FileManagerAdapter.GGGG>() {

    private val TAG = "FileManagerAdapter"
    private var showSelect: Boolean = false
    private var currentDir = Environment.getExternalStorageDirectory()
    private val cannotNextFiles = arrayListOf<File>()
    private var canNext: Boolean = true
    private val fileList = arrayListOf<FileBean>()

    inner class GGGG(view: View) : ViewHolder(view) {
        val binding = ItemFileManagerListBinding.bind(view)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GGGG {
        return GGGG(R.layout.item_file_manager_list.inflate(parent))
    }

    override fun getItemCount(): Int {
        return fileList.size
    }

    override fun onBindViewHolder(holder: GGGG, position: Int) {

    }

    private fun bindIcon(data: FileBean, iv: ImageView) {
        val file = File(data.path)
        when {
            isDir(file) -> iv.setImageResource(R.mipmap.dir)
            isImage(file) or isVideo(file) -> {
                Glide.with(iv.context)
                    .load(data.path)
                    .centerCrop()
                    .into(iv)
            }

            isAudio(file) -> iv.setImageResource(R.mipmap.audio)
            isZip(file) -> iv.setImageResource(R.mipmap.zip)
            isApk(file) -> iv.setImageResource(R.mipmap.apk)
            isDocument(file) -> iv.setImageResource(R.mipmap.file)
            else -> iv.setImageResource(R.mipmap.file)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: GGGG, position: Int, payloads: MutableList<Any>) {
        val data = fileList[position]
        val context = holder.binding.root.context

        if (payloads.isEmpty()) {
            bindIcon(data, holder.binding.iv)
            holder.binding.tvName.text = data.name
            val file = File(data.path)
            val timeE = SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH).format(file.lastModified())
            if (file.isFile) {
                val sizeF = file.length().toFormatSize()
                holder.binding.tvInfo.text = "$timeE  $sizeF"
            } else {
                val count = file.list()?.size ?: 0
                holder.binding.tvInfo.text = "$timeE  $count items"
            }

            //================================是否显示选中按钮逻辑==================================
            if (showSelect) {
                val drawable = ContextCompat.getDrawable(context, R.drawable.bg_selected)
                holder.binding.ivSelector.isSelected = data.isSelect
                holder.binding.ivSelector.isVisible = true
                holder.binding.ivSelector.setImageDrawable(drawable)
                holder.binding.ivSelector.setOnClickListener {
                    data.isSelect = !data.isSelect
                    holder.binding.ivSelector.isSelected = data.isSelect
                    notifyItemChanged(position, "sdada")
                    allSelect.invoke(fileList.all { it.isSelect })
                }
            } else {
                val drawable = ContextCompat.getDrawable(context, R.mipmap.jiantou_b)
                holder.binding.ivSelector.setImageDrawable(drawable)
                holder.binding.ivSelector.isVisible = file.isDirectory
                holder.binding.ivSelector.setOnClickListener { }
            }
            //============================选中目录无法再进入子目录逻辑==============================
            holder.binding.root.setOnClickListener {
                if (!cannotNextFiles.contains(file) && file.isDirectory && canNext)
                    nextPage(file)
            }
            if (cannotNextFiles.contains(file) && file.isDirectory) {
                val color = ContextCompat.getColor(context, R.color.color_6e6e6e)
                holder.binding.llItem.setBackgroundColor(color)
            } else {
                val color = ContextCompat.getColor(context, R.color.white)
                holder.binding.llItem.setBackgroundColor(color)
            }

        } else {
            holder.binding.root.setOnClickListener {
                holder.binding.ivSelector.isSelected = data.isSelect
            }
            super.onBindViewHolder(holder, position, payloads)
        }
    }

    private fun nextPage(file: File) {
        currentDir = file
        val files = currentDir.listFiles()
        val data = files?.map { FileBean(it.name, it.path, it.length()) } ?: listOf()
        setData(data, isEmpty = { showEmpty?.invoke(it) })
    }

    fun getCurrentDir(): File {
        return currentDir
    }

    fun notifyCurrentDir() {
        val files = currentDir.listFiles()
//        files?.sortByDescending { it.lastModified() }
        val data = files?.map { FileBean(it.name, it.path, it.length()) } ?: listOf()
        setData(data, isEmpty = { showEmpty?.invoke(it) })
    }

    fun changeSelect(
        isSelect: Boolean,
        isAddCannotNext: Boolean = false,
        isRemoveCannotNext: Boolean = false,
        canNext: Boolean = true,
    ) {
        showSelect = isSelect
        if (isAddCannotNext) {
            cannotNextFiles.addAll(getSelectData().map { File(it.path) })
        }
        if (isRemoveCannotNext) {
            cannotNextFiles.clear()
        }
        this.canNext = canNext
        notifyDataSetChanged()
    }

    fun getSelectData(): List<FileBean> {
        return fileList.filter { it.isSelect }
    }


    /**
     *@param 是否是根目录
     */
    fun beforePage(): Boolean {
        return if (currentDir.absoluteFile == Environment.getExternalStorageDirectory().absoluteFile) {
            true
        } else {
            currentDir = currentDir.parentFile
            val files = currentDir.listFiles()
            val data = files?.map { FileBean(it.name, it.path, it.length()) } ?: listOf()
            setData(data, isEmpty = { showEmpty?.invoke(it) })
            false
        }
    }

    fun setData(data: List<FileBean>, isEmpty: ((flag: Boolean) -> Unit)? = null) {
        fileList.clear()
        fileList.addAll(data)
        notifyDataSetChanged()
        isEmpty?.invoke(fileList.isEmpty())
    }


    fun getOperationList(): ArrayList<File> {
        return cannotNextFiles
    }

    fun toggleSelect(select: Boolean) {
        fileList.forEach { fileBean ->
            fileBean.isSelect = select
        }
        notifyDataSetChanged()
    }
}