namespace EEMSUIClient.Services;

public sealed class TrayController
{
    private TaskbarIcon? _tray;

    private bool disposedValue;

    public TaskbarIcon? Tray
    {
        set
        {
            ObjectDisposedException.ThrowIf(disposedValue, nameof(_tray));
            _tray = value;
        }
    }

    public bool IsExiting { get; private set; }

    public void HideToTray()
    {
        var mainWindow = (MainWindow)Application.Current.MainWindow;
        mainWindow.ShowInTaskbar = false;
        mainWindow.Hide();
    }

    public void ShowMainWindow()
    {
        var mainWindow = (MainWindow)Application.Current.MainWindow;
        if (!mainWindow.IsVisible)
        {
            mainWindow.Show();
        }
        mainWindow.WindowState = WindowState.Normal;
        mainWindow.ShowInTaskbar = true;
        mainWindow.Activate();
        mainWindow.Topmost = true;
        mainWindow.Topmost = false;
        mainWindow.Focus();
    }

    public void Exit()
    {
        IsExiting = true;
        Application.Current.MainWindow?.Close();
        Application.Current.Shutdown();
    }

    public void ShowBalloonTip()
    {
        _tray?.ShowBalloonTip("EEMS Client", "服务正在后台运行...", BalloonIcon.Info);
    }

    private void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // TODO: dispose managed state (managed objects)
                if (_tray != null)
                {
                    _tray.Visibility = Visibility.Hidden;
                    _tray.Dispose();
                    _tray = null;
                }
            }

            // TODO: free unmanaged resources (unmanaged objects) and override finalizer
            // TODO: set large fields to null
            disposedValue = true;
        }
    }

    // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
    // ~TrayController()
    // {
    //     // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
    //     Dispose(disposing: false);
    // }

    public void Dispose()
    {
        // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }
}
