package com.swago.room.pk

import android.os.Bundle
import android.view.Gravity
import androidx.fragment.app.viewModels
import com.swago.baseswago.baseroom.RoomTimer
import com.swago.baseswago.dialog.BaseXDFragment
import com.swago.baseswago.model.live.pk.SendPKModel
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.NoDoubleClickListener
import com.swago.loadUrl
import com.swago.room.R
import com.swago.room.databinding.DialogPkAcceptBinding

class PKAcceptDialog : BaseXDFragment<DialogPkAcceptBinding>(), RoomTimer.TimeTickListener {

    private val pkVm by viewModels<PkVm>()
    private var timeCount = 30
    private var sendPKModel :SendPKModel? = null

    init {
        setGravity(Gravity.BOTTOM)
        setCanCancel(false)
        setDimAmount(0f)
    }

    companion object{
        fun newInstance(sendPKModel: SendPKModel): PKAcceptDialog {
            val args = Bundle()
            args.putParcelable("sendPKModel",sendPKModel)
            val fragment = PKAcceptDialog()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initOther() {
        RoomTimer.timeTickList.add(this)
        arguments?.let {
            sendPKModel = it.getParcelable("sendPKModel")
            sendPKModel?.apply {
                context?.let { context ->
                    binding.tvSelfName.text = this.receiverName
                    binding.ivSelf.loadUrl(context,this.receiverAvatar)

                    binding.tvPeerName.text = this.senderName
                    binding.ivPeer.loadUrl(context,this.senderAvatar)

                    binding.tvTitle.text = AppContext.getContext().resources.getString(R.string.invites_you_to_pk).format(this.senderName)
                }
            }

            binding.tvAccept.setOnClickListener(object:NoDoubleClickListener(){
                override fun onClick() {
                    sendPKModel?.let {
                        pkVm.acceptPKOrRefusePK(1,it.senderId)
                        dismissAllowingStateLoss()
                    }
                }
            })

            binding.tvRefuse.setOnClickListener(object:NoDoubleClickListener(){
                override fun onClick() {
                    sendPKModel?.let {
                        pkVm.acceptPKOrRefusePK(2,it.senderId)
                        dismissAllowingStateLoss()
                    }
                }
            })
        }
    }

    override fun initLiveData() {

    }

    override fun onDestroyView() {
        RoomTimer.timeTickList.remove(this)
        super.onDestroyView()
    }

    override fun onTimeCount(time: Int) {
        timeCount--
        if (timeCount==0){
            dismissAllowingStateLoss()
        }
    }
}