package com.ypsx.yppos.ui.popup

import android.app.Activity
import android.content.Context
import android.view.Gravity
import android.view.View
import androidx.lifecycle.viewModelScope
import com.ypsx.base.base.appContext
import com.ypsx.base.ext.util.screenWidth
import com.ypsx.yppos.R
import com.ypsx.yppos.databinding.PopupPaySuccessBinding
import com.ypsx.yppos.viewmodel.state.PaySuccessViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import razerdp.basepopup.BasePopupWindow
import java.util.*

class PaySuccessPopWindow(context: Context) : BasePopupWindow(context) {
    lateinit var bind: PopupPaySuccessBinding
    var timer: Timer? = null
    var task: TimerTask? = null
    var recLen = 5
    lateinit var activity: Activity



    init {
        setContentView(R.layout.popup_pay_success)
        width = appContext.screenWidth / 4 * 3
        popupGravity = Gravity.CENTER
        isOutSideTouchable = false
        setOutSideDismiss(false)

    }

    private fun stopTimer() {
        if (task != null && timer != null) {
            timer?.cancel()
            timer?.purge()
            timer = null
            task = null
        }
    }

    override fun onViewCreated(contentView: View) {
        bind = PopupPaySuccessBinding.bind(contentView)
        bind.vm = PaySuccessViewModel()
        bind.click = ProxyClick()
        activity = context


        timer = Timer()
        task = object : TimerTask() {
            override fun run() {
                recLen--
                if (recLen < 0) {
                    if (isShowing) {
                        activity.runOnUiThread {
                            dismiss()
                        }
                    }
                    stopTimer()
                }
            }
        }
        timer?.schedule(task, 1000, 1000);
    }

    fun setData(total: String) {
        bind.vm?.amount?.set(total)
    }

    override fun dismiss() {
        super.dismiss()
        stopTimer()
    }


    inner class ProxyClick {
        fun close() {
            dismiss()
        }

    }
}