package com.base.datarecovery.utils

import android.provider.MediaStore
import com.base.datarecovery.bean.ImageInfoBean
import com.base.datarecovery.help.BaseApplication
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

object SimarPhotoUtils {
    val similarImageList = mutableListOf<ImageInfoBean>()
    fun getImageFiles(callback: () -> Unit) {
        MainScope().launch(Dispatchers.Main) {
            try {
                val imageList = mutableListOf<String>()
                val query = BaseApplication.context.contentResolver.query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    arrayOf(MediaStore.Files.FileColumns.DATA),
                    null,
                    null,
                    "${MediaStore.Files.FileColumns.DATE_MODIFIED} DESC"
                ) ?: return@launch
                while (query.moveToNext()) {
                    imageList.add(query.getString(0))
                }
                query.close()
                val imageDataList = mutableListOf<ImageInfoBean>()
                imageDataList.addAll(imageList.mapNotNull { ImageHelper.createImage(it) })
                imageDataList.sortBy { it.hashCode }

                similarImageList.clear()
                var index1 = 0
                var index2 = 1
                val similarItem = mutableListOf<ImageInfoBean>()
                while (index2 < imageDataList.size) {
                    val first = imageDataList[index1]
                    val second = imageDataList[index2]
                    if (ImageHelper.similarCondition(first, second)) {
                        if (similarItem.indexOf(first) < 0) {
                            similarItem.add(first)
                        }
                        if (similarItem.indexOf(second) < 0) {
                            similarItem.add(second)
                        }
                    } else {
                        if (similarItem.size > 1) {
                            similarImageList.addAll(similarItem)
                        }
                        similarItem.clear()
                    }
                    index1++
                    index2++
                }
                if (similarItem.size > 1) {
                    similarImageList.addAll(similarItem)
                }
            }catch (_:Exception){

            }
            callback()
        }
    }
}