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


import android.Manifest
import android.animation.Animator
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.text.format.Formatter
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.zxhyis.tools.R
import com.zxhyis.tools.base.TopActivity
import com.zxhyis.tools.databinding.ActivityDocumentsBinding
import com.zxhyis.tools.logic.AudioBean
import com.zxhyis.tools.logic.Counts
import com.zxhyis.tools.logic.Logic
import com.zxhyis.tools.logic.setOnClick
import com.zxhyis.tools.logic.setStatusBarTextDark
import com.zxhyis.tools.logic.showToast
import com.zxhyis.tools.logic.startActivity
import com.zxhyis.tools.logic.testLog
import com.zxhyis.tools.ui.adapter.ZipAdapter
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
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.BasicFileAttributes
import java.sql.Date
import java.text.SimpleDateFormat

class DocumentsActivity : TopActivity<ActivityDocumentsBinding>() {

    private val docList = ArrayList<AudioBean>()
    private val fileList = ArrayList<File>()
    private lateinit var docAdapter: ZipAdapter
    private var allSize = 0L
    private var dialog: LoadingDialog? = null
    private val result =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {}
    private var needRefresh = false


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

    override fun init() {

        vb.tvSet.setOnClick {
            vb.tvSet.setBackgroundResource(R.drawable.bg_shape_set_click)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                result.launch(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION))
            } else {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    ), Counts.REQUEST_ALL_FILE
                )
            }
        }

        vb.inDoc.imageSelectAll.setOnClick {
            fileList.clear()
            vb.inDoc.imageSelectAll.isSelected = !vb.inDoc.imageSelectAll.isSelected
            if (vb.inDoc.imageSelectAll.isSelected) {
                docAdapter.selectAll()
                for (audio in docList) {
                    fileList.add(audio.file)
                }
                vb.btDelete.setBackgroundResource(R.drawable.bg_shape_set)
            } else {
                docAdapter.deselectAll()
                for (audio in docList) {
                    fileList.remove(audio.file)
                }
                vb.btDelete.setBackgroundResource(R.drawable.bg_shape_delete_no)
            }
            testLog("${fileList.size}")
        }

        vb.inDoc.tvMenu.setOnClick {
            needRefresh = true
            if (docList.size > 0) {
                vb.inDoc.ivBack.visibility = View.GONE
                vb.inDoc.tvMenu.visibility = View.GONE
                vb.inDoc.imageSelectAll.visibility = View.VISIBLE
                vb.inDoc.tvAll.visibility = View.VISIBLE
                vb.btDelete.visibility = View.VISIBLE
                vb.inDoc.tvTitle.text = getString(R.string.select_zip_file)
                docAdapter.setShow()
            } else {
                getString(R.string.file_not_found).showToast()
            }
        }

        vb.btDelete.setOnClick {
            if (isCanDelete()) {
                CoroutineScope(Dispatchers.IO).launch {
                    delay(500)
                    deleteFiles()
                    launch(Dispatchers.Main) {
                        updateUI()
                    }
                }
            } else {
                "Please select at least one".showToast()
            }
        }

        vb.imageLoad.addAnimatorListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {}

            override fun onAnimationEnd(animation: Animator) {
                lifecycleScope.launch {
                    delay(500)
                    startActivity<ResultActivity>("from" to "doc")
                    finish()
                }
            }

            override fun onAnimationCancel(animation: Animator) {}

            override fun onAnimationRepeat(animation: Animator) {}

        })

        vb.inDoc.ivBack.setOnClick {
            finish()
        }

    }

    @SuppressLint("Recycle")
    private fun initData() {
        CoroutineScope(Dispatchers.IO).launch {
            delay(500)
            val contentResolver: ContentResolver = contentResolver
            val uri: Uri = MediaStore.Files.getContentUri("external")
            val projection = arrayOf(
                MediaStore.Files.FileColumns._ID,
                MediaStore.Files.FileColumns.DISPLAY_NAME,
                MediaStore.Files.FileColumns.SIZE,
                MediaStore.Files.FileColumns.DATA
            )
            val selection = (MediaStore.Files.FileColumns.MIME_TYPE + "=? OR " +
                    MediaStore.Files.FileColumns.MIME_TYPE + "=?")
            val selectionArgs = arrayOf(
                "text/plain",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            )
            val sortOrder = "${MediaStore.Files.FileColumns.DATE_MODIFIED} DESC"
            val cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder)

            cursor?.use {
                val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID)
                val nameColumn =
                    cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME)
                val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE)
                val dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA)

                while (cursor.moveToNext()) {
                    val id = cursor.getLong(idColumn)
                    val name = cursor.getString(nameColumn)
                    val size = cursor.getLong(sizeColumn)
                    val data = cursor.getString(dataColumn)
                    testLog("DocumentFiles,ID: $id,name:$name,size:$size,data:$data")
                    val file = File(name)
                    docList.add(
                        AudioBean(
                            file.absolutePath,
                            name,
                            Uri.parse(file.absolutePath),
                            file,
                            size,
                            apkTime = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
                                file.absolutePath
                            )
                            else "",
                            needRefresh
                        )
                    )
                    allSize += size
                }
            }

            docAdapter = ZipAdapter(docList, this@DocumentsActivity,1, object : Logic {
                override fun doLogic() {
                    remove()
                    if (fileList.size > 0) {
                        vb.btDelete.setBackgroundResource(R.drawable.bg_shape_set)
                    } else {
                        vb.btDelete.setBackgroundResource(R.drawable.bg_shape_delete_no)
                    }
                }

            })

            launch(Dispatchers.Main) {
                if (docList.size > 0) {
                    val linearLayoutManager = LinearLayoutManager(this@DocumentsActivity)
                    linearLayoutManager.initialPrefetchItemCount = 10
                    vb.rvDoc.apply {
                        layoutManager = linearLayoutManager
                        setHasFixedSize(true)
                        setItemViewCacheSize(20)
                        adapter = docAdapter
                    }
                    vb.apply {
                        rvDoc.visibility = View.VISIBLE
                        icNoFile.visibility = View.GONE
                        tvNoFile.visibility = View.GONE
                        totalSize.text = Formatter.formatFileSize(this@DocumentsActivity, allSize)
                    }
                } else {
                    vb.apply {
                        rvDoc.visibility = View.GONE
                        icNoFile.visibility = View.VISIBLE
                        tvNoFile.visibility = View.VISIBLE
                        totalSize.visibility = View.GONE
                    }
                }
                dialog?.dismiss()
            }
        }
    }

    private fun updateUI() {
        vb.imageLoad.visibility = View.VISIBLE
        vb.tvLoad.visibility = View.VISIBLE
        vb.imageLoad.playAnimation()
        vb.rvDoc.visibility = View.GONE
        vb.inDoc.clInclude.visibility = View.GONE
        vb.btDelete.visibility = View.GONE
        vb.totalSize.visibility = View.GONE
    }

    @SuppressLint("SimpleDateFormat")
    @RequiresApi(Build.VERSION_CODES.O)
    fun getFileCreationTime(filePath: String): String? {
        try {
            val path = Paths.get(filePath)
            val attr = Files.readAttributes(path, BasicFileAttributes::class.java)
            val creationTime = attr.creationTime()
            val date = Date(creationTime.toMillis())
            val format = SimpleDateFormat("yyyy-MM-dd HH:mm")
            return format.format(date)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    private fun isCanDelete(): Boolean {
        return fileList.size > 0
    }

    private fun remove() {
        fileList.clear()
        for (audio in docList) {
            if (audio.isSelected) {
                fileList.add(audio.file)
            } else {
                fileList.remove(audio.file)
            }
        }
    }

    private fun deleteFiles() {
        for (file in fileList) {
            file.delete()
        }
    }

    override fun onResume() {
        super.onResume()
        setStatusBarTextDark(this)
        allSize = 0
        docList.clear()
        fileList.clear()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                vb.apply {
                    imagePer.visibility = View.GONE
                    tvDes.visibility = View.GONE
                    tvSet.visibility = View.GONE
                    rvDoc.visibility = View.VISIBLE
                    totalSize.visibility = View.VISIBLE
                    initData()
                    dialog = LoadingDialog()
                    dialog?.isCancelable = false
                    dialog?.showNow(supportFragmentManager, "loading")
                }
            } else {
                vb.apply {
                    imagePer.visibility = View.VISIBLE
                    tvDes.visibility = View.VISIBLE
                    tvSet.visibility = View.VISIBLE
                    vb.tvSet.setBackgroundResource(R.drawable.bg_shape_set)
                    rvDoc.visibility = View.GONE
                    totalSize.visibility = View.GONE
                }
            }
        } else {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                vb.apply {
                    imagePer.visibility = View.VISIBLE
                    tvDes.visibility = View.VISIBLE
                    tvSet.visibility = View.VISIBLE
                    vb.tvSet.setBackgroundResource(R.drawable.bg_shape_set)
                    rvDoc.visibility = View.GONE
                    totalSize.visibility = View.GONE
                }
            } else {
                vb.apply {
                    imagePer.visibility = View.GONE
                    tvDes.visibility = View.GONE
                    tvSet.visibility = View.GONE
                    rvDoc.visibility = View.VISIBLE
                    totalSize.visibility = View.VISIBLE
                    initData()
                    dialog = LoadingDialog()
                    dialog?.isCancelable = false
                    dialog?.showNow(supportFragmentManager, "loading")
                }
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        docList.clear()
        fileList.clear()
        if (dialog != null) {
            dialog?.dismiss()
        }
    }

}