package com.base.scanqr.ui.widget

import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.Gravity
import android.view.LayoutInflater
import com.base.scanqr.R
import com.base.scanqr.databinding.DialogRateStarBinding
import com.base.scanqr.utils.AppPreferences

object RateDialog {

    fun Context.showRateDialog(mustShow: Boolean = false) {
        if (!mustShow) {
            if (AppPreferences.getInstance().getBoolean("isRated", false)) {
                return
            }
        }

        val dialog = AlertDialog.Builder(this).create()
        val binding = DialogRateStarBinding.inflate(LayoutInflater.from(this))
        dialog.setView(binding.root)
        dialog.setCanceledOnTouchOutside(true)

        dialog.show()

        val params = dialog.window?.attributes
//        params?.width = resources.getDimensionPixelOffset(R.dimen.dp_320)
//        params?.height = LinearLayout.LayoutParams.WRAP_CONTENT
        params?.gravity = Gravity.BOTTOM
        params?.y = 50

        dialog.window?.attributes = params
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)

        listOf(
            binding.iv1,
            binding.iv2,
            binding.iv3,
            binding.iv4,
            binding.iv5
        ).forEachIndexed { index, it ->
            it.setOnClickListener {
                setStar(binding, index)
            }
        }
        binding.ivClose.setOnClickListener {
            dialog.dismiss()
        }
        binding.tvRate.setOnClickListener {
            if (star >= 5) {
                AppPreferences.getInstance().put("isRated", true)
                try {
                    val uri =
                        Uri.parse("https://play.google.com/store/apps/details?id=" + this.packageName)
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    this.startActivity(intent)
                } catch (_: Exception) {
                }
            }
            dialog.dismiss()
        }
        dialog.setOnDismissListener {
            AppPreferences.getInstance().put("isRated", true)
        }
    }

    private var star = 5
    private fun setStar(binding: DialogRateStarBinding, star: Int) {
        this.star = star + 1
//        if (this.star < 3) {
//            binding.ivFace.setImageResource(R.mipmap.pingfeniconk)
//        } else {
//            binding.ivFace.setImageResource(R.mipmap.pingfenicon)
//        }

        listOf(
            binding.iv1,
            binding.iv2,
            binding.iv3,
            binding.iv4,
            binding.iv5
        ).forEachIndexed { index, it ->
            it.setImageResource(
                if (index <= star) {
                    R.mipmap.xing_s
                } else {
                    R.mipmap.xing_n
                }
            )
        }
    }
}