package com.aves.google_cast.cast

import android.app.Activity
import android.content.Context
import com.google.android.gms.cast.framework.CastContext
import com.google.android.gms.cast.framework.CastSession
import com.google.android.gms.cast.framework.SessionManagerListener
import com.google.android.gms.cast.framework.media.RemoteMediaClient

class CastContextManager(
    private val context: Context,
    private val sessionListener: SessionManagerListener<CastSession>
) {
    private var castContext: CastContext? = null
    private var currentActivity: Activity? = null
    private var sessionListenerAdded = false

    fun attachActivity(activity: Activity) {
        currentActivity = activity
        ensureCastContext()
    }

    fun detachActivity() {
        currentActivity = null
    }

    fun getSession(): CastSession? {
        ensureCastContext()
        return castContext?.sessionManager?.currentCastSession
    }

    fun getClient(): RemoteMediaClient? {
        return getSession()?.remoteMediaClient
    }

    fun ensureCastContext(): CastContext? {
        val activity = currentActivity ?: return null

        try {
            if (castContext == null) {
                castContext = CastContext.getSharedInstance(activity)
            }

            if (!sessionListenerAdded) {
                castContext!!.sessionManager.addSessionManagerListener(
                    sessionListener,
                    CastSession::class.java
                )
                sessionListenerAdded = true
            }
        } catch (_: Exception) {
            return null
        }

        return castContext
    }
}
