package com.base.appzxhy.ui.dialog

import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import com.base.appzxhy.R
import com.base.appzxhy.SpConstObject.scoreRate
import com.base.appzxhy.databinding.DialogRateBinding
import androidx.core.net.toUri
import com.base.appzxhy.SpConstObject.isScoreRated

class RateDialog(
    val activity: Activity
) {
    val dialog = AlertDialog.Builder(activity).create()
    val binding = DialogRateBinding.inflate(LayoutInflater.from(activity))

    var action: (() -> Unit)? = null

    fun showDialog(isMust: Boolean) {

        if (!isMust) {
            if (isScoreRated || scoreRate == 5)
                return
        }
        dialog.setView(binding.root)
        dialog.setCanceledOnTouchOutside(true)

        val params = dialog.window?.attributes
//        params?.width = activity.resources.getDimensionPixelSize(R.dimen.dp_300)
//        params?.width = FrameLayout.LayoutParams.WRAP_CONTENT
//        params?.height = FrameLayout.LayoutParams.WRAP_CONTENT
//        params?.gravity = Gravity.CENTER
        dialog.window?.attributes = params
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)

        dialog.show()

//        val appName = activity.getString(R.string.app_name)
//        val thankTip = activity.getString(R.string.thank_you_for_using_app, appName)
//        binding.tvThank.text = thankTip
        binding.ivClose.setOnClickListener {
            dialog.dismiss()
        }

        var score = 0
        val starList = listOf(
            binding.star1,
            binding.star2,
            binding.star3,
            binding.star4,
            binding.star5,
        )

        starList.forEachIndexed { index, view ->
            view.setOnClickListener {
                starList.forEachIndexed { index2, view2 ->
                    view2.setImageResource(if (index2 <= index) R.drawable.icon_star_s else R.drawable.icon_star_n)
                }
                score = index + 1
            }
        }
        binding.tvSubmit.setOnClickListener {
            scoreRate = score
            try {
                val url = "https://play.google.com/store/apps/details?id=${activity.packageName}"
                activity.startActivity(Intent(Intent.ACTION_VIEW, url.toUri()))
                isScoreRated = true
            } catch (_: Exception) {
            }
            dialog.dismiss()
        }
        binding.star5.callOnClick()

    }
}