package com.hmg.hmgDr.Service

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.Bundle
import android.os.IBinder
import com.hmg.hmgDr.MainActivity
import com.hmg.hmgDr.ui.VideoCallResponseListener
import com.hmg.hmgDr.ui.fragment.VideoCallFragment

class VideoStreamContainerService : Service(), VideoCallResponseListener {

    var videoCallResponseListener: VideoCallResponseListener? = null
    var mActivity: MainActivity? = null
        set(value) {
            field = value
            if (field != null) {
                setDialogFragment()
            }
        }
    var arguments: Bundle? = null
    var serviceRunning: Boolean = false


    private val serviceBinder: IBinder = VideoStreamBinder()
    private var dialogFragment: VideoCallFragment? = null

    override fun onBind(intent: Intent?): IBinder {
        return serviceBinder
    }

    private fun setDialogFragment() {
        mActivity?.run {
            if (dialogFragment == null) {
                val transaction = supportFragmentManager.beginTransaction()
                dialogFragment = VideoCallFragment.newInstance(arguments!!)
                dialogFragment?.let {
                    it.setCallListener(this@VideoStreamContainerService)
                    it.isCancelable = true
                    if (it.isAdded) {
                        it.dismiss()
                    } else {
                        it.show(transaction, "dialog")
                    }
                }
            } else if (!dialogFragment!!.isVisible) {
                val transaction = supportFragmentManager.beginTransaction()
                dialogFragment!!.show(transaction, "dialog")
            } else {
                // don't do anything
            }
        }
    }

    fun closeVideoCall(){
        dialogFragment?.onCallClicked()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent != null && intent.extras != null) {
            arguments = intent.extras
        }
//        Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show()
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
//        Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show()
    }

    inner class VideoStreamBinder : Binder() {
        val service: VideoStreamContainerService
            get() = this@VideoStreamContainerService
    }

    override fun onCallFinished(resultCode: Int, intent: Intent?) {
        dialogFragment = null
        videoCallResponseListener?.onCallFinished(resultCode, intent)
    }

    override fun errorHandle(message: String) {
        dialogFragment = null
//        Toast.makeText(this, message, Toast.LENGTH_LONG).show()
    }

    override fun minimizeVideoEvent(isMinimize: Boolean) {
        videoCallResponseListener?.minimizeVideoEvent(isMinimize)
    }
}