using System;
using System.Threading;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;

public class ConnectionKiller : MonoBehaviour {
    private static readonly CancellationTokenSource EagleGlobalShutdownTokenSource = new();
    public static CancellationToken EagleCancellationToken => EagleGlobalShutdownTokenSource.Token;

    public void OnApplicationQuit() { ShutdownAll(); }

#if UNITY_EDITOR
    void OnEnable() { EditorApplication.playModeStateChanged += OnPlayModeStateChanged; }

    void OnDisable() { EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; }

    void OnPlayModeStateChanged(PlayModeStateChange state) {
        if (state == PlayModeStateChange.ExitingPlayMode) { ShutdownAll(); }
    }
#endif

    public static void ShutdownAll() {
        Console.Out.WriteLine("Attempting GRPC shutdown.");
        EagleGlobalShutdownTokenSource.Cancel();
        Console.Out.WriteLine("Successfully shut down.");
    }
}
