package com.zxhyis.tools.ui.`fun`


import android.annotation.SuppressLint
import android.content.ContentResolver
import android.database.Cursor
import android.net.Uri
import android.os.Environment
import android.os.StatFs
import android.provider.MediaStore
import android.text.format.Formatter
import com.bumptech.glide.Glide
import com.zxhyis.tools.R
import com.zxhyis.tools.base.TopActivity
import com.zxhyis.tools.databinding.ActivityStorageInfoBinding
import com.zxhyis.tools.logic.setOnClick
import com.zxhyis.tools.logic.startActivity
import com.zxhyis.tools.logic.testLog
import com.zxhyis.tools.ui.dialog.LoadingDialog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

class StorageInfoActivity : TopActivity<ActivityStorageInfoBinding>() {

    private var dialog: LoadingDialog? = null
    private var pictureSize1=0L
    private var videoSize1=0L
    private var audioSize1=0L
    private var docSize1=0L
    private var apkSize1=0L
    private var zipSize1=0L
    private var otherSize1=0L



    override fun getViewBinding1(): ActivityStorageInfoBinding {
        return ActivityStorageInfoBinding.inflate(layoutInflater)
    }

    @SuppressLint("Recycle")
    override fun init() {
        dialog = LoadingDialog()
        dialog?.isCancelable = false
        dialog?.showNow(supportFragmentManager, "loading")

        Glide.with(this)
            .asGif()
            .load(R.drawable.start)
            .into(vb.ivStart)

        Glide.with(this)
            .asGif()
            .load(R.drawable.end)
            .into(vb.ivEnd)

        vb.ivBack.setOnClick {
            finish()
        }

        vb.btGoClean.setOnClick {
            vb.btGoClean.setBackgroundResource(R.drawable.bg_shape_set_click)
            startActivity<JunkCleanActivity>()
        }

        vb.tvTitle.text= getString(R.string.tv_storage)

        CoroutineScope(Dispatchers.IO).launch {
            delay(1000)
            val projection = arrayOf(MediaStore.Images.Media.DATA)
            val pictureCursor = contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection,
                null,
                null,
                null
            )
            pictureCursor?.let {
                val columnIndex = pictureCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                while (pictureCursor.moveToNext()) {
                    val imagePath = pictureCursor.getString(columnIndex)
                    val file = File(imagePath)
                    val fileSize=file.length()
                    pictureSize1+=fileSize
                }
            }
            pictureCursor?.close()

            val projection1 = arrayOf(MediaStore.Video.Media._ID,MediaStore.Video.Media.SIZE)
            val videoQuery = contentResolver.query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                projection1,
                null,
                null,
                null
            )
            videoQuery?.use { videoCursor ->
                val sizeColumn = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE)
                while (videoCursor.moveToNext()) {
                    val size = videoCursor.getLong(sizeColumn)
                    videoSize1 += size
                }
                videoCursor.close()
            }

            val contentResolver: ContentResolver = contentResolver
            val uri: Uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
            val projection2 = arrayOf(MediaStore.Audio.AudioColumns.DATA)
            val sortOrder2 = "${MediaStore.Audio.AudioColumns.TITLE} ASC"
            val cursor2: Cursor? =
                contentResolver.query(uri, projection2, null, null, sortOrder2)
            if (cursor2 != null && cursor2.moveToFirst()) {
                val dataIndex =
                    cursor2.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA)
                do {
                    val audioPath = cursor2.getString(dataIndex)
                    val file = File(audioPath)
                    audioSize1 += file.length()
                } while (cursor2.moveToNext())
                cursor2.close()
            }

            val docUri: Uri = MediaStore.Files.getContentUri("external")
            val docProjection = arrayOf(
                MediaStore.Files.FileColumns._ID,
                MediaStore.Files.FileColumns.DISPLAY_NAME,
                MediaStore.Files.FileColumns.SIZE,
                MediaStore.Files.FileColumns.DATA
            )
            val docSelection = (MediaStore.Files.FileColumns.MIME_TYPE + "=? OR " +
                    MediaStore.Files.FileColumns.MIME_TYPE + "=?")
            val selectionArgs = arrayOf(
                "text/plain",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            )
            val docSortOrder = "${MediaStore.Files.FileColumns.DATE_MODIFIED} DESC"
            val docCursor = contentResolver.query(docUri, docProjection, docSelection, selectionArgs, docSortOrder)
            docCursor?.use {
                val sizeColumn = docCursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE)
                while (docCursor.moveToNext()) {
                    val size = docCursor.getLong(sizeColumn)
                    docSize1 += size
                }
            }

            val zipUri: Uri = MediaStore.Files.getContentUri("external")
            val zipProjection = arrayOf(MediaStore.Files.FileColumns.DATA)
            val zipSelection = MediaStore.Files.FileColumns.MIME_TYPE + "=?"
            val zipsSelectionArgs = arrayOf("application/zip")
            val zipSortOrder = null
            val zipCursor: Cursor? = contentResolver.query(
                zipUri, zipProjection, zipSelection, zipsSelectionArgs, zipSortOrder
            )
            zipCursor?.use {
                val columnIndex = zipCursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)
                while (zipCursor.moveToNext()) {
                    val filePath = zipCursor.getString(columnIndex)
                    val file = File(filePath)
                    val fileSize=file.length()
                    zipSize1 +=fileSize
                }
                zipCursor.close()
            }

            val directory = File("/storage/emulated/0")
            if (directory.exists() && directory.isDirectory) {
                val files = directory.listFiles()//  /storage/emulated/0
                if (files != null) {
                    for (file in files) {
                        if (file.exists() && file.isDirectory) {
                            for (app in file.absoluteFile.listFiles()!!) {
                                if (app.isFile && app.name.endsWith(".apk")) {
                                    apkSize1 += app.length()
                                }
                            }
                        }
                    }
                }
            }

            val root = Environment.getExternalStorageDirectory()
            val queue = ArrayDeque<File>()
            queue.add(root)
            while (queue.isNotEmpty()) {
                val current = queue.removeFirst()
                val files = current.listFiles()
                if (files != null) {
                    for (file in files) {
                        if (file.isDirectory) {
                            queue.add(file)
                        } else if (file.isFile && file.length() == 0L) {
                            otherSize1+=file.length()
                        }
                    }
                }
            }

            dialog?.dismiss()

            launch(Dispatchers.Main) {
                vb.apply {
                    pictureSize.text=Formatter.formatFileSize(this@StorageInfoActivity,pictureSize1)
                    videoSize.text=Formatter.formatFileSize(this@StorageInfoActivity,videoSize1)
                    audioSize.text=Formatter.formatFileSize(this@StorageInfoActivity,audioSize1)
                    docSize.text=Formatter.formatFileSize(this@StorageInfoActivity,docSize1)
                    apkSize.text=Formatter.formatFileSize(this@StorageInfoActivity,apkSize1)
                    zipSize.text=Formatter.formatFileSize(this@StorageInfoActivity,zipSize1)
                    otherSize.text=Formatter.formatFileSize(this@StorageInfoActivity,otherSize1)
                    useSize.text=Formatter.formatFileSize(this@StorageInfoActivity,StatFs(Environment.getExternalStorageDirectory().path).availableBytes)
                }
            }
        }


    }

    @SuppressLint("SetTextI18n")
    private fun initStorage(){
        val stat = StatFs(Environment.getExternalStorageDirectory().path)
        val totalSize = stat.totalBytes
        val availableSize = stat.availableBytes
        val usedSize = totalSize - availableSize
        val usedPercentage = usedSize.toFloat() / totalSize * 100
        vb.pbTool.progress = usedPercentage.toInt()
        vb.tvPercent.text= "${usedPercentage.toInt()}"
        vb.tvStorage.text=
            "${Formatter.formatFileSize(this, usedSize)}/${Formatter.formatFileSize(this, totalSize)}"
        vb.btGoClean.setBackgroundResource(R.drawable.bg_shape_set)
    }

    override fun onResume() {
        super.onResume()
        initStorage()
    }

}