package kr.co.vividnext.sodalive.live.roulette

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.Window
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.FragmentActivity
import kr.co.vividnext.sodalive.databinding.DialogRouletteSpinBinding
import kr.co.vividnext.sodalive.extensions.dpToPx

class RouletteSpinDialog(
    private val activity: FragmentActivity,
    private val items: List<RouletteItem>,
    private val selectedItem: String,
    layoutInflater: LayoutInflater,
    private val complete: () -> Unit
) {
    private val alertDialog: AlertDialog
    private val dialogView = DialogRouletteSpinBinding.inflate(layoutInflater)
    private val handler = Handler(Looper.getMainLooper())

    init {
        val dialogBuilder = AlertDialog.Builder(activity)
        dialogBuilder.setView(dialogView.root)

        alertDialog = dialogBuilder.create()
        alertDialog.setCancelable(false)
        alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        alertDialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        setupView()
    }

    fun show() {
        alertDialog.show()

        val lp = WindowManager.LayoutParams()
        lp.copyFrom(alertDialog.window?.attributes)
        lp.width = activity.resources.displayMetrics.widthPixels - (26.7f.dpToPx()).toInt()
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT

        alertDialog.window?.attributes = lp
        rotateToOption()
    }

    private fun setupView() {
        dialogView.roulette.items = items
    }

    private fun rotateToOption() {
        dialogView.roulette.rotateToOption(selectedItem) {
            handler.postDelayed({
                alertDialog.dismiss()
                complete()
            }, 1500)
        }
    }
}
