package com.nhnkcp.verifonepossample.utils

import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object ViewUtils {
    fun View.hideKeyboard() {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(windowToken, 0)
    }

    suspend fun showSnackBar(view: View, msg: String) {
        withContext(Dispatchers.Main) {
            Snackbar.make(view, msg, Snackbar.LENGTH_LONG)
                .setTextMaxLines(20) // 표시될 최대 줄 수
                .show()
        }
    }

    class OnSingleClickListener(private val onSingleClick: (View) -> Unit) : View.OnClickListener {
        private var lastClickedTime: Long = 0

        override fun onClick(view: View) {
            // 중복클릭을 방지하기 위해 1초안에 클릭시 이벤트 미전달
            if (System.currentTimeMillis() - lastClickedTime > 1000)
                onSingleClick(view)
            lastClickedTime = System.currentTimeMillis()
        }
    }

    fun View.setOnSingleClickListener(block: () -> Unit) {
        val clickListener = OnSingleClickListener { block() }
        setOnClickListener(clickListener)
    }
}