package com.zxhy.fastfilemanagerpro.kokodup

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zxhy.fastfilemanagerpro.CommonViewModel
import com.zxhy.fastfilemanagerpro.kokodata.KoFileDatako
import com.zxhy.fastfilemanagerpro.kokodata.KoFileDatako.Companion.toFile
import com.zxhy.fastfilemanagerpro.kokotools.Md5Ex.byteArrayToHexString
import com.zxhy.fastfilemanagerpro.kokotools.Md5Ex.digestMd5
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class KoDupFilekoViewModel : CommonViewModel() {
    fun isImageFilter(file: File): Boolean {
        return file.name.contains(".jpg") or
                file.name.contains(".gif") or
                file.name.contains(".png")
    }

    fun isDupFileFilter(file: File): Boolean {
        return file.length() > 0 && !isImageFilter(file)

    }


    fun loadDupImage(
        context: Context,
        onFinish: (list: List<KoDupFileDatako>) -> Unit
    ) = viewModelScope.launch(Dispatchers.IO) {

        loadAllFile(context, ::isImageFilter) { list ->
            onFinish.invoke(calculateDup(list))
        }
    }

    fun loadDupFile(
        context: Context,
        onFinish: (list: List<KoDupFileDatako>) -> Unit
    ) = viewModelScope.launch(Dispatchers.IO) {

        loadAllFile(context, ::isDupFileFilter) { list ->
            onFinish.invoke(calculateDup(list))
        }
    }


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

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

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


}