package kr.co.vividnext.sodalive.settings.notification

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

class NotificationSettingsDialog(
    activity: Activity,
    layoutInflater: LayoutInflater,
    confirmAction: (Boolean, Boolean, Boolean) -> Unit
) {

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

    private var isNewChannelLive = true
    private var isNotifiedChannel = true
    private var isMessage = true

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

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

        dialogView.ivNewChannelLive.setOnClickListener {
            isNewChannelLive = !isNewChannelLive
            dialogView.ivNewChannelLive.setImageResource(
                if (isNewChannelLive) {
                    R.drawable.btn_toggle_on_big
                } else {
                    R.drawable.btn_toggle_off_big
                }
            )
        }

        dialogView.ivNotifiedChannel.setOnClickListener {
            isNotifiedChannel = !isNotifiedChannel
            dialogView.ivNotifiedChannel.setImageResource(
                if (isNotifiedChannel) {
                    R.drawable.btn_toggle_on_big
                } else {
                    R.drawable.btn_toggle_off_big
                }
            )
        }

        dialogView.ivMessage.setOnClickListener {
            isMessage = !isMessage
            dialogView.ivMessage.setImageResource(
                if (isMessage) {
                    R.drawable.btn_toggle_on_big
                } else {
                    R.drawable.btn_toggle_off_big
                }
            )
        }

        dialogView.tvConfirm.setOnClickListener {
            confirmAction(isNewChannelLive, isNotifiedChannel, isMessage)
            alertDialog.dismiss()
        }
    }

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