package rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.LifecycleCoroutineScope
import com.base.datarecovery.R
import com.base.datarecovery.databinding.AdoptedtoBinding
import com.base.datarecovery.databinding.GlimpseedtoBinding
import com.base.datarecovery.databinding.HarmonyedtoBinding
import com.base.datarecovery.databinding.HilledtoBinding
import com.base.datarecovery.databinding.KeptedtoBinding
import com.base.datarecovery.databinding.LegislationedtoBinding
import com.base.datarecovery.databinding.MagnetedtoBinding
import com.base.datarecovery.databinding.RelinquishedtoBinding
import com.base.datarecovery.databinding.WalkedtoBinding
import com.base.datarecovery.databinding.WeighedtoBinding
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import rowedto.jockeyedto.sheetedto.atticedto.directionedto.noxiousedto.batedto.Celebrationedto
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SELECT_FILE_ALL
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SELECT_FILE_AUDIO
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SELECT_FILE_DOCUMENT
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SELECT_FILE_OTHER
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SELECT_FILE_PICTURE
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SELECT_FILE_VIDEO
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Dishedto
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.Scandaledto
import java.io.File
import kotlin.random.Random

object Patedto {

    private val TAG = "DialogViews"

    @SuppressLint("SetTextI18n")
    fun Context.showGerPermission(
        tittle: String? = null,
        desc: String? = null,
        denyText: String? = null,
        allowText: String? = null,
        deny: ((view: Dialog) -> Unit)? = null,
        allow: ((view: Dialog) -> Unit)? = null
    ): Dialog {
        val dialog = Dialog(this)
        val binding = MagnetedtoBinding.inflate(LayoutInflater.from(this))
        dialog.requestWindowFeature(1)
        dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.window!!.setLayout(-1, -1)
        dialog.setCanceledOnTouchOutside(false)
        dialog.setCancelable(false)
        dialog.setContentView(binding.root)
        val str = resources.getString(R.string.overchargeedto)

        tittle?.let { binding.indirectedto.text = it }
        desc?.let { binding.vatedto.text = it }
        denyText?.let { binding.divorceedto.text = it }
        allowText?.let { binding.traitedto.text = it }

        binding.mistreatedto.imageAssetsFolder = "recovery_permission_finger/images/"
        binding.mistreatedto.setAnimation("recovery_permission_finger/data.json")
        binding.mistreatedto.playAnimation()
        binding.divorceedto.setOnClickListener {
            dialog.dismiss()
            deny?.invoke(dialog)
        }
        binding.traitedto.setOnClickListener {
            dialog.dismiss()
            allow?.invoke(dialog)
        }
        dialog.show()
        return dialog
    }


    @SuppressLint("SetTextI18n")
    fun Context.showRecoveringDialog(
        lifecycleScope: LifecycleCoroutineScope,
        list: List<String>,
        dir: File,
        copyProgressAction: () -> Unit,
        finish: () -> Unit
    ) {
        val dialog = BottomSheetDialog(this)
        val binding = AdoptedtoBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(false)

        val mutableSharedFlow = MutableSharedFlow<Int>(
            replay = 5,//当新的订阅者Collect时，发送几个已经发送过的数据给它
            extraBufferCapacity = 5,//减去replay，MutableSharedFlow还缓存多少数据,缓冲池容量 = replay + extraBufferCapacity
            onBufferOverflow = BufferOverflow.SUSPEND//缓存策略，三种 丢掉最新值、丢掉最旧值和挂起
        )
        val sharedFlow: SharedFlow<Int> = mutableSharedFlow

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED
        // 设置禁止通过拖动来隐藏
        behavior.isHideable = false

        // 禁止点击外部区域关闭
        dialog.setOnCancelListener { dialogInterface ->
            dialogInterface.cancel() // 这里可以处理点击外部区域的逻辑
        }

        lifecycleScope.launch(Dispatchers.IO) {

            val arrayList = arrayListOf<String>().apply {
                addAll(list)
            }
            var index = 0
            while (arrayList.isNotEmpty()) {
                val path = arrayList[0]
                arrayList.removeAt(0)
                val file = File(path)
                runCatching {
                    val recoveryFile = File(dir, file.name)
                    file.copyTo(recoveryFile, true)
                }
                mutableSharedFlow.emit(index)
                delay(Random.nextLong(500, 1500))
                index++
            }
            mutableSharedFlow.emit(-1)
        }

        lifecycleScope.launch(Dispatchers.Main) {
            sharedFlow.collectLatest {
                Dishedto.logDebug(TAG, "Flow $it")
                if (it == -1) {
                    finish.invoke()
                    dialog.dismiss()
                    cancel()
                } else {
                    val process = it.toFloat() / list.size.toFloat()
                    if (process > 0.3) {
                        copyProgressAction.invoke()
                    }
                    binding.appetiteedto.text = "${it + 1}/${list.size}"
                }
            }
        }

        dialog.show()
    }


    fun Context.showImageImportDialog(import: () -> Unit, camera: () -> Unit) {
        val binding = LegislationedtoBinding.inflate(LayoutInflater.from(this))
        val dialog =
            AlertDialog.Builder(this, R.style.assertiveedto).setView(binding.root).create()

        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()

        val params = dialog.window?.attributes
        params?.gravity = Gravity.BOTTOM
        params?.y = 50

        dialog.window?.attributes = params

        binding.restedto.setOnClickListener {
            dialog.dismiss()
            import.invoke()
        }
        binding.infrastructureedto.setOnClickListener {
            dialog.dismiss()
            camera.invoke()
        }
    }

    fun Context.showCameraSettingDialog() {
        val binding = HilledtoBinding.inflate(LayoutInflater.from(this))
        val dialog =
            AlertDialog.Builder(this, R.style.assertiveedto).setView(binding.root).create()

        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()

        val params = dialog.window?.attributes

        dialog.window?.attributes = params
        binding.dangerousedto.setOnClickListener { dialog.dismiss() }
    }

    fun Context.showRemoveOriginalTip(click: (isRememberOption: Boolean, isRemove: Boolean) -> Unit) {
        val binding = WalkedtoBinding.inflate(LayoutInflater.from(this))
        val dialog = AlertDialog.Builder(this, R.style.assertiveedto).create()

        dialog.setView(binding.root)
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()

        val params = dialog.window?.attributes
        params?.width = resources.getDimensionPixelOffset(R.dimen.drewedto)
        dialog.window?.attributes = params

        binding.relationshipedto.setOnClickListener {
            binding.relationshipedto.isSelected = !binding.relationshipedto.isSelected
        }

        binding.griefedto.setOnClickListener {
            dialog.dismiss()
            click.invoke(binding.relationshipedto.isSelected, true)
        }
        binding.byedto.setOnClickListener {
            dialog.dismiss()
            click.invoke(binding.relationshipedto.isSelected, false)
        }
    }

    fun Context.showPinReEnterDialog(): Standardedto {
        val dialog = Standardedto(this, R.layout.extensionedto)
        dialog.window?.setDimAmount(0f)
        dialog.show()
        return dialog
    }

    fun Context.showDeletePermanentlyDialog(deleteAction: () -> Unit) {
        val binding = KeptedtoBinding.inflate(LayoutInflater.from(this))
        val dialog = AlertDialog.Builder(this, R.style.assertiveedto).create()
        dialog.setView(binding.root)
        dialog.show()


        val params = dialog.window?.attributes
        params?.width = resources.getDimensionPixelOffset(R.dimen.drewedto)
        dialog.window?.attributes = params

        binding.kineticedto.setOnClickListener {
            dialog.cancel()
            deleteAction.invoke()
        }
        binding.lowedto.setOnClickListener {
            dialog.cancel()
        }
    }

    fun Context.showExitFunctionDialog(
        mustShow: Boolean = false,
        exitAction: (showAd: Boolean) -> Unit
    ) {
        if (!mustShow) {
            if (!Scandaledto.showBackInterAdSp()) {
                exitAction.invoke(false)
                return
            }
        }

        val binding = GlimpseedtoBinding.inflate(LayoutInflater.from(this))
        val dialog = AlertDialog.Builder(this).create()
        dialog.setView(binding.root)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()

        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
        val params = dialog.window?.attributes
        params?.width = resources.getDimensionPixelOffset(R.dimen.sectionedto)
        dialog.window?.attributes = params
        Scandaledto.admobMaxShowNativeAd(this as Activity,binding.tooledto,1)
        binding.originaledto.setOnClickListener {
            dialog.dismiss()
            exitAction.invoke(true)
        }
        binding.talkedto.setOnClickListener {
            dialog.dismiss()
        }
    }

    fun Activity.showExitDialog() {
        val binding = WeighedtoBinding.inflate(LayoutInflater.from(this))
        val dialog = AlertDialog.Builder(this).create()
        dialog.setView(binding.root)
//        dialog.setCanceledOnTouchOutside(false)
//        dialog.setCancelable(false)
        dialog.show()


        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
        val lp: WindowManager.LayoutParams? = dialog.window?.attributes
        lp?.gravity = Gravity.BOTTOM
        lp?.width = ConstraintLayout.LayoutParams.MATCH_PARENT
//        lp?.alpha = 1f
//        lp?.dimAmount = 0.0f
        dialog.window?.setAttributes(lp)

        binding.talkedto.setOnClickListener {
            dialog.dismiss()
            startActivity(Intent(this, Celebrationedto::class.java))
        }


        binding.commitmentedto.setOnClickListener {
            dialog.dismiss()
//            android.os.Process.killProcess(android.os.Process.myPid())
//            System.exit(0)
            this.finish()
        }
    }

    fun Context.showLargeFileTypeDialog(type: String, click: (type: String) -> Unit) {
        val binding = RelinquishedtoBinding.inflate(LayoutInflater.from(this))
        val dialog = AlertDialog.Builder(this).create()
        dialog.setView(binding.root)
//        dialog.setCanceledOnTouchOutside(false)
//        dialog.setCancelable(false)
        dialog.show()

        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
        val lp: WindowManager.LayoutParams? = dialog.window?.attributes
        lp?.gravity = Gravity.BOTTOM
        lp?.width = ConstraintLayout.LayoutParams.MATCH_PARENT
        dialog.window?.setAttributes(lp)

        when (type) {
            SELECT_FILE_ALL -> binding.warnedto.isSelected = true
            SELECT_FILE_PICTURE -> binding.matteredto.isSelected = true
            SELECT_FILE_VIDEO -> binding.panedto.isSelected = true
            SELECT_FILE_AUDIO -> binding.metropolisedto.isSelected = true
            SELECT_FILE_DOCUMENT -> binding.foundationedto.isSelected = true
            SELECT_FILE_OTHER -> binding.hopeedto.isSelected = true
        }
        binding.warnedto.setOnClickListener {
            dialog.dismiss()
            click.invoke(SELECT_FILE_ALL)
        }
        binding.matteredto.setOnClickListener {
            dialog.dismiss()
            click.invoke(SELECT_FILE_PICTURE)
        }
        binding.panedto.setOnClickListener {
            dialog.dismiss()
            click.invoke(SELECT_FILE_VIDEO)
        }
        binding.metropolisedto.setOnClickListener {
            dialog.dismiss()
            click.invoke(SELECT_FILE_AUDIO)
        }
        binding.foundationedto.setOnClickListener {
            dialog.dismiss()
            click.invoke(SELECT_FILE_DOCUMENT)
        }
        binding.hopeedto.setOnClickListener {
            dialog.dismiss()
            click.invoke(SELECT_FILE_OTHER)
        }
    }

    @SuppressLint("SetTextI18n")
    fun Context.showAppProcessExitDialog(percent: Int, action: () -> Unit) {
        val binding = HarmonyedtoBinding.inflate(LayoutInflater.from(this))
        val dialog = AlertDialog.Builder(this).create()
        dialog.setView(binding.root)
        dialog.show()
        val text = "RAM accounts for more than $percent%.\nAre you sure want to leave?"
        val spannableString = SpannableString(text)

        val start = text.indexOf("$percent%")
        val end = start + "$percent%".length
        spannableString.setSpan(ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        binding.overedto.text = spannableString
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
        val lp: WindowManager.LayoutParams? = dialog.window?.attributes

        lp?.width = this.resources.getDimensionPixelOffset(R.dimen.confidenceedto)
//        lp?.height=

        dialog.window?.setAttributes(lp)
        binding.originaledto.setOnClickListener {
            dialog.dismiss()
            action.invoke()
        }
        binding.talkedto.setOnClickListener {
            dialog.dismiss()
        }
    }

}
