package rallyedto.talledto.blewedto

import android.provider.MediaStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import rallyedto.battleedto.acresedto.Criticismedto
import rallyedto.policeedto.huntedto.Squeezeedto

object Lampedto {
    val similarImageList = mutableListOf<Squeezeedto>()
    fun getImageFiles(callback: () -> Unit) {
        MainScope().launch(Dispatchers.Main) {
            try {
                val imageList = mutableListOf<String>()
                val query = Criticismedto.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<Squeezeedto>()
                imageDataList.addAll(imageList.mapNotNull { Telledto.createImage(it) })
                imageDataList.sortBy { it.hashCode }

                similarImageList.clear()
                var index1 = 0
                var index2 = 1
                val similarItem = mutableListOf<Squeezeedto>()
                while (index2 < imageDataList.size) {
                    val first = imageDataList[index1]
                    val second = imageDataList[index2]
                    if (Telledto.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()
        }
    }
}