package com.zxhy.simplefilesmanager.simpledup

import com.zxhy.simplefilesmanager.simpleCommon.SimpleCommonViewModel
import com.zxhy.simplefilesmanager.simpledata.JoDupFileJo
import com.zxhy.simplefilesmanager.simpledata.JoGridFileJo.Companion.joGridFileJo
import com.zxhy.simplefilesmanager.simpledata.JoFileJo.Companion.isImage
import com.zxhy.simplefilesmanager.simpledata.JoGridFileJo
import com.zxhy.simplefilesmanager.simplejoke.JoMd5Ex.toHexString
import com.zxhy.simplefilesmanager.simplejoke.JoMd5Ex.partDigestMd5

class SimpleDupViewModel : SimpleCommonViewModel() {


    fun loadDup(onFinish: (list: List<JoDupFileJo>) -> Unit) = loadFile(::isImage, ::joGridFileJo) {
        val dups = calculateDup(it)
        onFinish.invoke(dups)
    }

    private fun calculateDup(data: List<JoGridFileJo>): List<JoDupFileJo> {
        val dupMap = HashMap<String, ArrayList<JoGridFileJo>>()

        data.forEach {
            val md5 = it.toFile().partDigestMd5().toHexString()
            val dupList = dupMap[md5]
            if (dupList == null) {
                val newList = arrayListOf<JoGridFileJo>()
                dupMap[md5] = newList
                newList.add(it)
            } else {
                dupList.add(it)
            }
        }

        val dupList = dupMap.filter { it.value.size > 1 }
            .map { map ->
                JoDupFileJo(md5 = map.key, dups = map.value)
            }
        return dupList
    }

}