package com.zxhyis.toolss.ui.page


import android.Manifest
import android.animation.Animator
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
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.toolss.R
import com.zxhyis.toolss.ad.AdmobUtils
import com.zxhyis.toolss.base.TopActivity
import com.zxhyis.toolss.databinding.ActivityZipFileBinding
import com.zxhyis.toolss.logic.AudioBean
import com.zxhyis.toolss.logic.Counts
import com.zxhyis.toolss.logic.DialogDismissListener
import com.zxhyis.toolss.logic.Logic
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.logic.setStatusBarTextDark
import com.zxhyis.toolss.logic.showToast
import com.zxhyis.toolss.logic.startActivity
import com.zxhyis.toolss.ui.adapter.ZipAdapter
import com.zxhyis.toolss.ui.dialog.LoadingDialog
import com.zxhyis.toolss.ui.page.result.ResultActivity
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("SimpleDateFormat")
class ZipFileActivity : TopActivity<ActivityZipFileBinding>(), DialogDismissListener {

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

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

    override fun init() {
        vb.inAudio.tvTitle.text = getString(R.string.tv_zip)
        setStatusBarTextDark(this)
        allSize = 0
        zipList.clear()
        fileList.clear()
        zipList.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
                    rvAudio.visibility = View.VISIBLE
                    totalSize.visibility = View.VISIBLE
                    initDatasource(this@ZipFileActivity)
                    dialog = LoadingDialog()
                    dialog?.setDismissListener(this@ZipFileActivity)
                    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)
                    rvAudio.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)
                    rvAudio.visibility = View.GONE
                    totalSize.visibility = View.GONE
                }
            } else {
                vb.apply {
                    imagePer.visibility = View.GONE
                    tvDes.visibility = View.GONE
                    tvSet.visibility = View.GONE
                    rvAudio.visibility = View.VISIBLE
                    totalSize.visibility = View.VISIBLE
                    initDatasource(this@ZipFileActivity)
                    dialog = LoadingDialog()
                    dialog?.setDismissListener(this@ZipFileActivity)
                    dialog?.isCancelable = false
                    dialog?.showNow(supportFragmentManager, "loading")
                }
            }
        }
        vb.inAudio.ivBack.setOnClick(javaClass.simpleName) {
            finish()
        }

        vb.tvSet.setOnClick(javaClass.simpleName) {
            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.inAudio.imageSelectAll.setOnClick(javaClass.simpleName) {
            fileList.clear()
            selectList.clear()
            vb.inAudio.imageSelectAll.isSelected = !vb.inAudio.imageSelectAll.isSelected
            if (vb.inAudio.imageSelectAll.isSelected) {
                zipAdapter.selectAll()
                for (audio in zipList) {
                    fileList.add(audio.file)
                    selectList.add(audio)
                }
                vb.btDelete.setBackgroundResource(R.drawable.bg_shape_set)
            } else {
                zipAdapter.deselectAll()
                for (audio in zipList) {
                    fileList.remove(audio.file)
                    selectList.remove(audio)
                }
                vb.btDelete.setBackgroundResource(R.drawable.bg_shape_delete_no)
            }
        }

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

        vb.btDelete.setOnClick(javaClass.simpleName) {
            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 "zip")
                    finish()
                }
            }

            override fun onAnimationCancel(animation: Animator) {}

            override fun onAnimationRepeat(animation: Animator) {}

        })

    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private fun initDatasource(context: Context) {
        CoroutineScope(Dispatchers.IO).launch {
            delay(500)

            val uri: Uri = MediaStore.Files.getContentUri("external")
            val projection = arrayOf(MediaStore.Files.FileColumns.DATA)
            val selection = MediaStore.Files.FileColumns.MIME_TYPE + "=?"
            val selectionArgs = arrayOf("application/zip")
            val sortOrder = null
            val cursor: Cursor? = context.contentResolver.query(
                uri, projection, selection, selectionArgs, sortOrder
            )
            cursor?.use {

                val columnIndex = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)

                while (cursor.moveToNext()) {
                    val filePath = cursor.getString(columnIndex)
                    val file = File(filePath)
                    zipList.add(
                        AudioBean(
                            filePath,
                            file.absoluteFile.name,
                            Uri.parse(filePath),
                            file,
                            file.length(),
                            apkTime = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
                                file.absolutePath
                            )
                            else "",
                            needRefresh
                        )
                    )
                    allSize = file.length()
                }
                cursor.close()
                zipAdapter = ZipAdapter(zipList, this@ZipFileActivity, 0, 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 (zipList.size > 0) {
                    val linearLayoutManager = LinearLayoutManager(this@ZipFileActivity)
                    linearLayoutManager.initialPrefetchItemCount = 10
                    vb.rvAudio.apply {
                        layoutManager = linearLayoutManager
                        setHasFixedSize(true)
                        setItemViewCacheSize(20)
                        adapter = zipAdapter
                    }
                    vb.apply {
                        rvAudio.visibility = View.VISIBLE
                        icNoFile.visibility = View.GONE
                        tvNoFile.visibility = View.GONE
                        totalSize.text = Formatter.formatFileSize(this@ZipFileActivity, allSize)
                    }
                } else {
                    vb.apply {
                        rvAudio.visibility = View.GONE
                        icNoFile.visibility = View.VISIBLE
                        tvNoFile.visibility = View.VISIBLE
                        totalSize.visibility = View.GONE
                    }
                }
                delay(1000)
                dialog?.dismiss()
            }
        }
    }

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


    @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()
        selectList.clear()
        for (audio in zipList) {
            if (audio.isSelected) {
                fileList.add(audio.file)
                selectList.add(audio)
            } else {
                fileList.remove(audio.file)
                selectList.remove(audio)
            }
        }
    }

    private fun deleteFiles() {
        for (file in fileList) {
            file.delete()
            val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
            val uri = Uri.fromFile(file)
            intent.data = uri
            sendBroadcast(intent)
        }
    }

    override fun onResume() {
        super.onResume()

    }

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

    override fun onDialogDismissed() {
        AdmobUtils.showInterstitialAd(this)
       // MaxAdUtils.showMaxInterstitialAd(this, "interstitial_slot")
    }


}