package com.base.datarecovery.view

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import com.base.datarecovery.R
import com.base.datarecovery.databinding.DialogRateStarBinding
import com.base.datarecovery.utils.SPUtils

object RateStarPop {

    @SuppressLint("SetTextI18n")
    fun Context.showRateStarPopDialog() {

        val n = SPUtils.getInstance().getInt("RateNumbers", 0)
        SPUtils.getInstance().put("RateNumbers", n + 1)
        if (SPUtils.getInstance().getBoolean("isRated", false)) {
            return
        }
        if (n > 0 && n % 8 == 0) {
            
        } else {
            return
        }


        val binding = DialogRateStarBinding.inflate(LayoutInflater.from(this))
        val dialog = AlertDialog.Builder(this).create()
        dialog.setView(binding.root)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
//        dialog.window?.setDimAmount(1f)
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)

        val appName = resources.getString(R.string.app_name)
        binding.tvTitle.text = "Thank you for using $appName"

        listOf(
            binding.idStar1,
            binding.idStar2,
            binding.idStar3,
            binding.idStar4,
            binding.idStar5
        ).forEachIndexed { index, it ->
            it.setOnClickListener {
                setStar(binding, index)
            }
        }
        binding.flClose.setOnClickListener {
            dialog.dismiss()
        }
        binding.tvSubmit.setOnClickListener {
            if (star >= 5) {
                SPUtils.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()
        }

    }

    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.idStar1,
            binding.idStar2,
            binding.idStar3,
            binding.idStar4,
            binding.idStar5
        ).forEachIndexed { index, it ->
            it.setImageResource(
                if (index <= star) {
                    R.mipmap.xing_s
                } else {
                    R.mipmap.xing_n
                }
            )
        }
    }
}