package com.base.browserwhite.ui.views

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import com.base.browserwhite.R
import com.base.browserwhite.databinding.DialogRateStarBinding
import com.base.browserwhite.utils.AppPreferences
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog

object RateDialog {

    @SuppressLint("SetTextI18n")
    fun Context.showRateDialog(mustShow: Boolean = false) {

        if (!mustShow) {
            if (AppPreferences.getInstance().getBoolean("isRated", false)) {
                return
            }
        }

        val dialog = BottomSheetDialog(this)
        val binding = DialogRateStarBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(false)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        binding.tvTittle.text = "Rate " + resources.getString(R.string.app_name)

        listOf(
            binding.idStar1,
            binding.idStar2,
            binding.idStar3,
            binding.idStar4,
            binding.idStar5
        ).forEachIndexed { index, it ->
            it.setOnClickListener {
                setStar(binding, index)
            }
        }
        binding.tvSubmit.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.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
                }
            )
        }
    }
}