package com.base.pdfviewerscannerwhite.ui.view

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

object RateDialog {

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

        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        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


        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.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.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
                }
            )
        }
    }
}