package melody.offline.music.view

import android.app.Dialog
import android.content.Context
import android.view.LayoutInflater
import melody.offline.music.R
import melody.offline.music.databinding.DialogRatingBinding
import melody.offline.music.util.AnalysisUtil
import melody.offline.music.util.openGooglePlay
import melody.offline.music.util.sendFeedback
import org.json.JSONObject

class RatingDialog(private val mContext: Context) : Dialog(mContext) {
    private var starType = 5
    private var binding: DialogRatingBinding =
        DialogRatingBinding.inflate(LayoutInflater.from(mContext))

    init {
        setContentView(binding.root)
        AnalysisUtil.logEvent(AnalysisUtil.RATING_DIALOG_SHOW)
        window?.setBackgroundDrawableResource(android.R.color.transparent)
        setCanceledOnTouchOutside(false)
        initClick()
    }

    private fun initClick() {
        binding.dialogOkBtn.setOnClickListener {
            when (starType) {
                1, 2, 3 -> {
                    sendFeedback(
                        mContext,
                        "motaleb3024@gmail.com",
                        mContext.getString(R.string.app_name)
                    )
                }

                4, 5 -> {
                    openGooglePlay(mContext, mContext.packageName)
                }
            }
            dismiss()

            val jsonObject = JSONObject()
            jsonObject.put(
                "rating_star_type", starType
            )
            val starMap = mutableMapOf(
                Pair(
                    AnalysisUtil.PARAM_VALUE, jsonObject.toString()
                )
            )
            AnalysisUtil.logEvent(AnalysisUtil.RATING_DIALOG_OK_CLICK, starMap)
        }
        binding.dialogCancelBtn.setOnClickListener {
            AnalysisUtil.logEvent(AnalysisUtil.RATING_DIALOG_CANCEL_CLICK)
            dismiss()
        }
        val stars =
            arrayOf(binding.star1, binding.star2, binding.star3, binding.star4, binding.star5)

        stars.forEachIndexed { index, imageView ->
            //由于数组索引从0开始，而星星的评分从1开始，因此需要将index加1
            imageView.setOnClickListener {
                starType = index + 1
                updateStarUi(starType)
            }
        }
    }

    private fun updateStarUi(type: Int) {
        val stars = arrayOf(
            binding.star1Img,
            binding.star2Img,
            binding.star3Img,
            binding.star4Img,
            binding.star5Img
        )
        stars.forEachIndexed { index, imageView ->
            //当前索引是否小于type，如果是，则表示该星星需要被选中，否则表示该星星未被选中。
            val resource =
                if (index < type) R.drawable.star_select_icon else R.drawable.star_unselect_icon
            imageView.setImageResource(resource)
        }
    }
}
