package kr.co.vividnext.sodalive.live.room.dialog

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 com.jakewharton.rxbinding4.widget.textChanges
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import kr.co.vividnext.sodalive.databinding.DialogLiveRoomPasswordBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.extensions.moneyFormat

class LiveRoomPasswordDialog(
    activity: Activity,
    layoutInflater: LayoutInflater,
    can: Int,
    confirmButtonClick: (String) -> Unit,
) {

    private val alertDialog: AlertDialog
    val dialogView = DialogLiveRoomPasswordBinding.inflate(layoutInflater)

    private val compositeDisposable = CompositeDisposable()

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

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

        if (can > 0) {
            dialogView.tvCan.visibility = View.VISIBLE
            dialogView.tvCan.text = can.moneyFormat()
            dialogView.tvConfirm.text = "으로 입장"
        } else {
            dialogView.tvCan.visibility = View.GONE
            dialogView.tvConfirm.text = "입장하기"
        }

        compositeDisposable.add(
            dialogView.etPassword.textChanges().skip(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    if (it.isNotEmpty()) {
                        try {
                            it.toString().toInt()
                        } catch (e: NumberFormatException) {
                            dialogView.etPassword.setText(it.substring(0, it.length - 1))
                        }
                    }
                }
        )
        dialogView.tvCancel.setOnClickListener { alertDialog.dismiss() }
        dialogView.llConfirm.setOnClickListener {
            alertDialog.dismiss()
            if (dialogView.etPassword.text.isNotBlank()) {
                confirmButtonClick(dialogView.etPassword.text.toString())
            } else {
                confirmButtonClick("")
            }
        }

        alertDialog.setOnDismissListener { compositeDisposable.clear() }
    }

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