package com.remax.visualnovel.app.widget.tips

import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.widget.PopupWindow
import android.widget.TextView
import androidx.annotation.StringRes
import com.remax.visualnovel.R
import com.remax.visualnovel.widget.ui.SwitchView

class TipsSwitchWindow {
    private var popupWindow: PopupWindow? = null

    fun build(
        context: Context,
        @StringRes tips: Int,
        isChecked: Boolean = false,
        switchCallback: (SwitchView,Boolean) -> Unit
    ): TipsSwitchWindow {
        val view = LayoutInflater.from(context).inflate(R.layout.popwindow_switch_tips, null)
        popupWindow = PopupWindow(context).apply {
            isFocusable = true
            contentView = view
            isOutsideTouchable = true
            setBackgroundDrawable(ColorDrawable())
        }
        view.findViewById<TextView>(R.id.tvContent).setText(tips)
        view.findViewById<SwitchView>(R.id.switchView).run {
            this.isChecked = isChecked
            setPressChanged { switchCallback(this,it) }
        }
        return this
    }

    fun showAsDropDown(view: View?) {
        if (popupWindow!!.isShowing) {
            popupWindow!!.dismiss()
        } else {
            popupWindow!!.showAsDropDown(view)
        }
    }

    fun showAsDropDown(view: View?, xoff: Int, yoff: Int) {
        if (popupWindow!!.isShowing) {
            popupWindow!!.dismiss()
        } else {
            popupWindow!!.showAsDropDown(view, xoff, yoff)
        }
    }

    fun showAtLocation(parent: View?, gravity: Int, x: Int, y: Int) {
        if (popupWindow!!.isShowing) {
            popupWindow!!.dismiss()
        } else {
            popupWindow!!.showAtLocation(parent, gravity, x, y)
        }
    }
}