package kr.co.vividnext.sodalive.base

import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import kr.co.vividnext.sodalive.databinding.DialogSodaBinding
import kr.co.vividnext.sodalive.extensions.dpToPx

open class SodaDialog(
    activity: Activity,
    layoutInflater: LayoutInflater,
    title: String,
    desc: String,
    confirmButtonTitle: String,
    confirmButtonClick: () -> Unit,
    cancelButtonTitle: String = "",
    cancelButtonClick: (() -> Unit)? = null,
) {

    private val alertDialog: AlertDialog

    val dialogView = DialogSodaBinding.inflate(layoutInflater)

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

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

        dialogView.tvTitle.text = title
        dialogView.tvDesc.text = desc

        dialogView.tvCancel.text = cancelButtonTitle
        dialogView.tvCancel.setOnClickListener {
            alertDialog.dismiss()
            cancelButtonClick?.let { it() }
        }

        dialogView.tvConfirm.text = confirmButtonTitle
        dialogView.tvConfirm.setOnClickListener {
            alertDialog.dismiss()
            confirmButtonClick()
        }

        dialogView.tvCancel.visibility = if (cancelButtonTitle.isNotBlank()) {
            View.VISIBLE
        } else {
            View.GONE
        }

        dialogView.tvConfirm.visibility = if (confirmButtonTitle.isNotBlank()) {
            View.VISIBLE
        } else {
            View.GONE
        }
    }

    fun show(width: Int) {
        alertDialog.show()

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

        alertDialog.window?.attributes = lp
    }
}
