@file:Suppress("DEPRECATION")

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


import android.Manifest
import android.animation.Animator
import android.animation.Animator.AnimatorListener
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
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.ActivityApkListBinding
import com.zxhyis.tools.logic.ApkInfoBean
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.shareMultipleApks
import com.zxhyis.tools.logic.showToast
import com.zxhyis.tools.logic.startActivity
import com.zxhyis.tools.logic.testLog
import com.zxhyis.tools.ui.adapter.ApkAdapter
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

@SuppressLint("NotifyDataSetChanged")
class ApkListActivity : TopActivity<ActivityApkListBinding>() {

    private val apkList = ArrayList<ApkInfoBean>()
    private val fileList = ArrayList<File>()
    private lateinit var apkAdapter: ApkAdapter
    private var allSize = 0L
    private var count=0
    private val result =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {}
    private var dialog: LoadingDialog? = null
    private var needRefresh=false

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


    override fun init() {

        vb.inApk.tvTitle.text = getString(R.string.tv_apk)

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

        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.inApk.imageSelectAll.setOnClick {
            fileList.clear()
            vb.inApk.imageSelectAll.isSelected = !vb.inApk.imageSelectAll.isSelected
            if (vb.inApk.imageSelectAll.isSelected) {
                apkAdapter.selectAll()
                for (apk in apkList){
                    fileList.add(apk.file)
                }
                vb.ivShare.setImageResource(R.drawable.ic_share_selected)
                vb.ivDelete.setImageResource(R.drawable.ic_delete_selected)
            } else {
                apkAdapter.deselectAll()
                for (apk in apkList){
                    fileList.remove(apk.file)
                }
                vb.ivShare.setImageResource(R.drawable.ic_share)
                vb.ivDelete.setImageResource(R.drawable.ic_delete)
            }
            testLog("${fileList.size}")
        }

        vb.inApk.tvMenu.setOnClick {
            needRefresh=true
            if (apkList.size > 0) {
                vb.inApk.ivBack.visibility = View.GONE
                vb.inApk.tvMenu.visibility = View.GONE
                vb.inApk.imageSelectAll.visibility = View.VISIBLE
                vb.inApk.tvAll.visibility = View.VISIBLE
                vb.llBottom.visibility = View.VISIBLE
                vb.inApk.tvTitle.text = getString(R.string.select_apk)
                apkAdapter.setShow()
            } else {
                getString(R.string.file_not_found).showToast()
            }
        }

        vb.ivDelete.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 :AnimatorListener{
            override fun onAnimationStart(animation: Animator) {}

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

            override fun onAnimationCancel(animation: Animator) {}

            override fun onAnimationRepeat(animation: Animator) {}

        })


        vb.ivShare.setOnClick {
            when {
                fileList.size in 1..3 -> {
                    shareMultipleApks(fileList,this)
                }

                fileList.size > 3 -> {
                    "Select up to three".showToast()
                }

                else -> {
                    "Select at least one".showToast()
                }
            }
        }



    }

    private fun updateUI(){
        vb.imageLoad.visibility=View.VISIBLE
        vb.tvLoad.visibility=View.VISIBLE
        vb.imageLoad.playAnimation()
        vb.rvApk.visibility=View.GONE
        vb.inApk.clInclude.visibility=View.GONE
        vb.llBottom.visibility=View.GONE
        vb.totalSize.visibility=View.GONE
    }

    @SuppressLint("UseCompatLoadingForDrawables", "SetTextI18n")
    private fun initDatasource() {
        CoroutineScope(Dispatchers.IO).launch {
            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")) {
                                    val pm = packageManager
                                    val info = pm.getPackageArchiveInfo(
                                        app.absolutePath,
                                        PackageManager.GET_ACTIVITIES
                                    )
                                    val appInfo = info?.applicationInfo
                                    appInfo?.sourceDir = app.absolutePath
                                    appInfo?.publicSourceDir = app.absolutePath
                                    allSize += app.length()
                                    apkList.add(
                                        ApkInfoBean(
                                            apkIcon = (if (appInfo != null) appInfo.loadIcon(pm) else getDrawable(
                                                R.drawable.ic_unknow
                                            ))!!,
                                            apkName = app.name,
                                            apkPath = "/${file.absoluteFile.name}/",
                                            apkSize = app.length(),
                                            apkTime = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
                                                file.absolutePath
                                            )
                                            else "",
                                            file = app,
                                            needRefresh
                                        )
                                    )
                                    count++
                                }
                            }
                        }
                    }
                }
            }

            apkAdapter = ApkAdapter(apkList, this@ApkListActivity, object : Logic {
                override fun doLogic() {
                    testLog("logic:${fileList.size}")
                    remove()
                    if (fileList.size > 0) {
                        vb.ivShare.setImageResource(R.drawable.ic_share_selected)
                        vb.ivDelete.setImageResource(R.drawable.ic_delete_selected)
                    } else {
                        vb.ivShare.setImageResource(R.drawable.ic_share)
                        vb.ivDelete.setImageResource(R.drawable.ic_delete)
                    }
                }

            })

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

    @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
    }

    override fun onResume() {
        super.onResume()
        setStatusBarTextDark(this)
        allSize=0
        apkList.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
                    rvApk.visibility = View.VISIBLE
                    totalSize.visibility = View.VISIBLE
                    initDatasource()
                    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)
                    rvApk.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)
                    rvApk.visibility = View.GONE
                    totalSize.visibility = View.GONE
                }
            } else {
                vb.apply {
                    imagePer.visibility = View.GONE
                    tvDes.visibility = View.GONE
                    tvSet.visibility = View.GONE
                    rvApk.visibility = View.VISIBLE
                    totalSize.visibility = View.VISIBLE
                    initDatasource()
                    dialog=LoadingDialog()
                    dialog?.isCancelable=false
                    dialog?.showNow(supportFragmentManager,"loading")
                }
            }
        }
    }

    private fun isCanDelete():Boolean{
        testLog("de:${fileList.size}")
        return fileList.size>0
    }

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

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

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

}