package com.zxhy.hfilemanagermaster.internalstorage

import android.annotation.SuppressLint
import android.content.Context
import android.os.Environment
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.hfilemanagermaster.R
import com.example.hfilemanagermaster.databinding.ItemFileSelectBinding
import com.zxhy.hfilemanagermaster.data.MediaDataC
import com.zxhy.hfilemanagermaster.data.file2MediaDataC
import com.zxhy.hfilemanagermaster.glide.loadIntoImageView
import com.zxhy.hfilemanagermaster.knife.inflate
import java.io.File

class FileAdapter(
    private val selectAction: ((flag: Boolean) -> Unit)? = null,
    private val nextPageAction: ((file: File) -> Unit)? = null,
    private val beforePageAction: ((file: File) -> Unit)? = null
) : RecyclerView.Adapter<FileAdapter.FileSelectViewHolder>() {
    private val mediaList = arrayListOf<MediaDataC>()
    private var isSelect = false
    private var currentDir: File = Environment.getExternalStorageDirectory()

    class FileSelectViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val binding = ItemFileSelectBinding.bind(view)
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): FileSelectViewHolder {
        val root = R.layout.item_file_select.inflate(parent)
        return FileSelectViewHolder(root)
    }

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

    override fun onBindViewHolder(holder: FileSelectViewHolder, position: Int) {
        val context = holder.binding.root.context
        val data = mediaList[position]

        holder.binding.apply {
            if (data.path.contains(".jpg")
                or
                data.path.contains(".mp4")
                or
                data.path.contains(".png")
            ) {
                loadIntoImageView(context, File(data.path), iv)
            } else if (data.path.contains(".txt")) {
                iv.setImageResource(R.mipmap.io_002)
            } else if (data.path.contains(".xlsx") or data.path.contains(".xls")) {
                iv.setImageResource(R.mipmap.as_85230)
            } else if (data.path.contains(".pdf")) {
                iv.setImageResource(R.mipmap.io_0012)
            } else if (data.path.contains(".ppt") or data.path.contains(".pptx")) {
                iv.setImageResource(R.mipmap.io_002223)
            } else if (data.path.contains(".apk")) {
                iv.setImageResource(R.mipmap.fe_98856)
            } else if (data.path.contains(".zip")) {
                iv.setImageResource(R.mipmap.qwett_98959)
            } else if (data.path.contains("log") && File(data.path).isFile) {
                iv.setImageResource(R.mipmap.rqwr_875)
            } else if (File(data.path).isDirectory) {
                iv.setImageResource(R.mipmap.tt_695)
            } else {
                iv.setImageResource(R.drawable.icon_file_unknown)
            }

            tvName.text = data.name
            tvSize.text = data.size
            ivSelector.isSelected = data.select
            flSelector.setOnClickListener {
                data.select = !data.select
                notifyItemChanged(position, "单条刷新")
            }
            ivSelector.visibility = if (isSelect) View.VISIBLE else View.GONE

            if (data == mediaList.last()) {
                selectAction?.invoke(mediaList.all { it.select })
            }
            root.setOnClickListener {
                nextPage(data, context)
            }
        }


    }

    override fun onBindViewHolder(
        holder: FileSelectViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        val context = holder.binding.root.context
        val data = mediaList[position]

        //判断是做局部刷新还是单条刷新
        if (payloads.isEmpty()) {//局部刷新
            holder.binding.apply {
                if (data.path.contains(".jpg")
                    or
                    data.path.contains(".mp4")
                    or
                    data.path.contains(".png")
                ) {
                    loadIntoImageView(context, File(data.path), iv)
                } else if (data.path.contains(".txt")) {
                    iv.setImageResource(R.mipmap.io_002)
                } else if (data.path.contains(".xlsx") or data.path.contains(".xls")) {
                    iv.setImageResource(R.mipmap.as_85230)
                } else if (data.path.contains(".pdf")) {
                    iv.setImageResource(R.mipmap.io_0012)
                } else if (data.path.contains(".ppt") or data.path.contains(".pptx")) {
                    iv.setImageResource(R.mipmap.io_002223)
                } else if (data.path.contains(".apk")) {
                    iv.setImageResource(R.mipmap.fe_98856)
                } else if (data.path.contains(".zip")) {
                    iv.setImageResource(R.mipmap.qwett_98959)
                } else if (data.path.contains("log") && File(data.path).isFile) {
                    iv.setImageResource(R.mipmap.rqwr_875)
                } else if (File(data.path).isDirectory) {
                    iv.setImageResource(R.mipmap.tt_695)
                } else {
                    iv.setImageResource(R.drawable.icon_file_unknown)
                }
                tvName.text = data.name
                tvSize.text = data.size
                ivSelector.isSelected = data.select
                flSelector.setOnClickListener {
                    data.select = !data.select
                    notifyItemChanged(position, "单条刷新")
                }
                if (data == mediaList.last()) {
                    selectAction?.invoke(mediaList.all { it.select })
                }
                root.setOnClickListener {
                    nextPage(data, context)
                }
                ivSelector.visibility = if (isSelect) View.VISIBLE else View.GONE
            }
        } else {// 单条刷新
            holder.binding.apply {
                ivSelector.isSelected = data.select
            }
            super.onBindViewHolder(holder, position, payloads)

            selectAction?.invoke(mediaList.all { it.select })
        }

    }

    @SuppressLint("NotifyDataSetChanged")
    fun setData(data: List<MediaDataC>) {
        mediaList.clear()
        mediaList.addAll(data)
        notifyDataSetChanged()
    }


    @SuppressLint("NotifyDataSetChanged")
    fun setToggleSelect(): Boolean {
        val flag = mediaList.all { it.select }
        mediaList.forEach { it.select = !flag }
        notifyDataSetChanged()
        return !flag
    }

    fun getSelectSize(): Int {
        return mediaList.count { it.select }
    }

    private fun nextPage(data: MediaDataC, context: Context) {
        val file = File(data.path)
        if (file.isDirectory) {
            val subList = file.listFiles()
            val subData = subList?.map { it.file2MediaDataC(context) } ?: listOf()
            setData(subData)
            nextPageAction?.invoke(file)
            currentDir = file
        }
    }

    fun beforePage(context: Context): Boolean {
//        Log.e("beforePage", "$currentDir")
        val parentDir = currentDir.parentFile ?: File("")
        if (parentDir.exists() && parentDir.isDirectory) {
            val subList = parentDir.listFiles()
            if (subList.isNullOrEmpty()) return false
            val subData = subList.map { it.file2MediaDataC(context) }
            setData(subData)
            beforePageAction?.invoke(parentDir)
            currentDir = parentDir
            return true
        } else {
            return false
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun showSelect() {
        isSelect = true
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun showNoSelect() {
        isSelect = false
        notifyDataSetChanged()
    }

    fun getSelectFile(): List<MediaDataC> {
        return mediaList.filter { it.select }
    }

    fun getSelectFileIndex(): List<MediaDataC> {
        return mediaList.filterIndexed { index, mediaDataC ->
            mediaDataC.index = index
            mediaDataC.select
        }
    }


    fun getCurrentDir(): File {
        return currentDir
    }

    fun notifyCurrentDir(context: Context) {
        val data = currentDir.listFiles()?.map { it.file2MediaDataC(context) } ?: listOf()
        setData(data)
    }

    @SuppressLint("NotifyDataSetChanged")
    fun removeData(file: List<MediaDataC>) {
        mediaList.removeAll(file.toSet())
//        file.forEachIndexed { index, mediaDataC ->
//            Log.e("removeData", "index=$index $mediaDataC")
//        }
        notifyDataSetChanged()
    }

    fun notifyItemIndex(data: MediaDataC) {
        mediaList[data.index].select = false
        notifyItemChanged(data.index, "单条刷洗")
    }

    @SuppressLint("NotifyDataSetChanged")
    fun notifyItemNoSelect() {
        mediaList.forEach { it.select = false }
        notifyDataSetChanged()
    }
}