package com.base.filerecoveryrecyclebin.utils

import android.graphics.BitmapFactory
import android.provider.MediaStore.Audio.Radio
import java.io.File
import kotlin.random.Random

object SimilarHelper {


    fun calculate(list: ArrayList<File>) {

        val result = HashMap<String, ArrayList<File>>()
        val eachArrayList = arrayListOf<File>().apply {
            addAll(list)
        }
        val comparedFile = arrayListOf<File>()

        val iterator = list.iterator()
        val compareIterator = eachArrayList.iterator()

        while (iterator.hasNext()) {
            val item = iterator.next()

            if (!comparedFile.contains(item)) {
                while (compareIterator.hasNext()) {
                    val compareItem = compareIterator.next()

                    if (item.absoluteFile != compareItem.absoluteFile) {

                        val percent = similarPercent(item, compareItem)
                        if (percent > 80) {
                            if (result[item.absolutePath] == null) {
                                result[item.absolutePath] = arrayListOf()
                            }
                            result[item.absolutePath]?.add(item)
                            result[item.absolutePath]?.add(compareItem)
                            comparedFile.add(compareItem)
                            compareIterator.remove()
                        }

                    }
                }
            }

        }

    }


    private fun similarPercent(srcFile: File, compareFile: File): Int {
        var similarityScore:Double = 0.00
        try {
            val bitmap1 = BitmapFactory.decodeFile(srcFile.absolutePath)
            val bitmap2 = BitmapFactory.decodeFile(compareFile.absolutePath)

            if (bitmap1.width != bitmap2.width || bitmap1.height != bitmap2.height) {
                return 0 // 如果尺寸不同，则直接返回0
            }

            var totalDifference = 0L
            for (x in 0 until bitmap1.width) {
                for (y in 0 until bitmap1.height) {
                    val pixel1 = bitmap1.getPixel(x, y)
                    val pixel2 = bitmap2.getPixel(x, y)
                    val redDifference = (pixel1 shr 16 and 0xff) - (pixel2 shr 16 and 0xff)
                    val greenDifference = (pixel1 shr 8 and 0xff) - (pixel2 shr 8 and 0xff)
                    val blueDifference = (pixel1 and 0xff) - (pixel2 and 0xff)
                    totalDifference += (redDifference * redDifference + greenDifference * greenDifference + blueDifference * blueDifference)
                }
            }

            // 计算相似度得分
            val maxDifference = bitmap1.width * bitmap1.height * 3 * 255 * 255
            similarityScore = (1 - totalDifference.toDouble() / maxDifference) * 100

        } catch (e: Exception) {
            e.printStackTrace()
        }

        // 将相似度得分四舍五入到整数
        return similarityScore.toInt().coerceIn(0, 100)
    }

}