package pxds.lmmd.zmwf

import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import com.blankj.utilcode.util.FileUtils
import com.test.basd.supercleanermax.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import pxds.lmmd.zmwf.Khko.string
import pxds.vazp.FileBean
import pxds.vazp.Xwft
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale
import kotlin.random.Random

object Oejm {

    val fileList = mutableListOf<FileBean>()

    val typeDateList = mutableListOf<Pair<String, MutableList<FileBean>>>()

    val similarImageList = mutableListOf<Xwft>()

    var allSize = 0L

    var freeSize = 0L

    private val dateFormat by lazy {
        SimpleDateFormat(R.string.ޞޘޑޅޜ_D.string(), Locale.getDefault())
    }

    var systemSize = 0L

    var usedSize = 0L

    fun getFileList(onUpdate: () -> Unit, onEnd: (() -> Unit)? = null) {
        MainScope().launch(Dispatchers.Main) {
            launch(Dispatchers.IO) {
                initFileList()
            }
            var emptyCount = 0
            var preSize = 0
            while (emptyCount < 12) {
                delay(Random.nextLong(400, 800))
                if (fileList.isNotEmpty()) {
                    if (fileList.size - preSize == 0) {
                        emptyCount++
                    } else {
                        emptyCount = 0
                        onUpdate()
                    }
                    preSize = fileList.size
                }

            }
            onEnd?.invoke()
        }
    }

    fun File.toBean() = FileBean(
        name = name, path = absolutePath, size = length(), isDir = isDirectory, type = if (TextUtils.isEmpty(
                FileUtils.getFileExtension(name).lowercase()
            )
        ) R.string.ގޅޑޡޛ_D.string() else FileUtils.getFileExtension(name).lowercase(), time = lastModified()
    )

    private fun initFileList(file: File) {
        if (file.isFile) {
            fileList.add(file.toBean())
        } else {
            file.listFiles()?.let {
                if (it.isEmpty()) {
                    fileList.add(file.toBean())
                } else {
                    for (i in it) {
                        initFileList(i)
                    }
                }
            }
        }
    }

    private fun initFileList() {
        if (fileList.isEmpty()) {
            initFileList(Environment.getExternalStorageDirectory())
        }
    }

    fun getTypeFiles(callback: () -> Unit) {
        MainScope().launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                val typeFiles = mutableListOf<String>()
                val query = Lwfm.context.contentResolver.query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.Files.FileColumns.DATA), null, null, R.string.ހޡވޤޛ_D.string((MediaStore.Files.FileColumns.DATE_MODIFIED).toString())
                ) ?: return@withContext
                while (query.moveToNext()) {
                    typeFiles.add(query.getString(0))
                }
                query.close()
                typeDateList.clear()
                typeFiles.forEach {
                    val fileBean = File(it).toBean()
                    val dateString = dateFormat.format(fileBean.time)
                    if (typeDateList.lastOrNull()?.first != dateString) {
                        typeDateList.add(Pair(dateString, mutableListOf()))
                    }
                    typeDateList.lastOrNull()?.second?.add(fileBean)
                }
                callback()
            }
        }

    }

    init {
        val root = Environment.getExternalStorageDirectory()
        freeSize = FileUtils.getFsAvailableSize(root.absolutePath)
        allSize = FileUtils.getFsTotalSize(root.absolutePath)
        usedSize = allSize - freeSize
        systemSize = FileUtils.getFsTotalSize(Environment.getRootDirectory().absolutePath)
    }

    fun deleteFile(fileOrDirectory: File): Boolean {
        if (fileOrDirectory.isDirectory)
            fileOrDirectory.listFiles()?.forEach { child -> deleteFile(child) }

        return fileOrDirectory.delete()
    }

    fun getImageFiles(callback: () -> Unit) {
        MainScope().launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                val imageList = mutableListOf<String>()
                val query = Lwfm.context.contentResolver.query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.Files.FileColumns.DATA), null, null, R.string.ހޡވޤޛ_D.string((MediaStore.Files.FileColumns.DATE_MODIFIED).toString())
                ) ?: return@withContext
                while (query.moveToNext()) {
                    imageList.add(query.getString(0))
                }
                query.close()
                val imageDataList = mutableListOf<Xwft>()
                imageDataList.addAll(imageList.mapNotNull { Wype.createImage(it) })
                imageDataList.sortBy { it.hashCode }

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