#nullable enable

using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;

public class TrayApp : ApplicationContext
{
    private NotifyIcon trayIcon;
    private Telemetry telemetry;
    private System.Windows.Forms.Timer timer;
    private bool telemetryPaused = false;

    public TrayApp()
    {
        telemetry = new Telemetry();
        telemetry.Initialize();

        trayIcon = new NotifyIcon()
        {
            Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath),
            Visible = true,
            Text = "Telemetry Running (UDP)"
        };

        var menu = new ContextMenuStrip();

        // Show config.json
        menu.Items.Add("Show Config", null, OnShowConfig);

        // Reload config
        menu.Items.Add("Reload Config", null, OnReloadConfig);

        // Separator
        menu.Items.Add(new ToolStripSeparator());

        // Exit
        menu.Items.Add("Exit", null, OnExit);

        trayIcon.ContextMenuStrip = menu;

        // Main telemetry timer
        timer = new System.Windows.Forms.Timer();
        timer.Interval = 1000;
        timer.Tick += (s, e) =>
        {
            if (!telemetryPaused)
                telemetry.UpdateAndSend();
        };
        timer.Start();

        // Detect system sleep/wake
        SystemEvents.PowerModeChanged += OnPowerModeChanged;
    }

    private void OnPowerModeChanged(object? sender, PowerModeChangedEventArgs e)
    {
        if (e.Mode == PowerModes.Suspend)
        {
            telemetryPaused = true;
        }
        else if (e.Mode == PowerModes.Resume)
        {
            telemetryPaused = true;

            // Give Windows time to restore networking
            var resumeTimer = new System.Windows.Forms.Timer();
            resumeTimer.Interval = 3000; // 3 seconds
            resumeTimer.Tick += (s, ev) =>
            {
                telemetryPaused = false;
                resumeTimer.Stop();
                resumeTimer.Dispose();
            };
            resumeTimer.Start();
        }
    }

    // Show config.json in Explorer
    private void OnShowConfig(object? sender, EventArgs e)
    {
        try
        {
            string exeDir = AppContext.BaseDirectory;
            string cfgPath = Path.Combine(exeDir, "config.json");

            if (File.Exists(cfgPath))
            {
                Process.Start("explorer.exe", $"/select,\"{cfgPath}\"");
            }
            else
            {
                MessageBox.Show(
                    "config.json not found.",
                    "Show Config",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning
                );
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(
                $"Failed to open config.json:\n{ex.Message}",
                "Show Config Error",
                MessageBoxButtons.OK,
                MessageBoxIcon.Error
            );
        }
    }

    // Reload config handler
    private void OnReloadConfig(object? sender, EventArgs e)
    {
        try
        {
            telemetry.Dispose();
            telemetry = new Telemetry();
            telemetry.Initialize();

            MessageBox.Show(
                "Configuration reloaded successfully.",
                "Reload Config",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information
            );
        }
        catch (Exception ex)
        {
            MessageBox.Show(
                $"Failed to reload configuration:\n{ex.Message}",
                "Reload Config Error",
                MessageBoxButtons.OK,
                MessageBoxIcon.Error
            );
        }
    }

    private void OnExit(object? sender, EventArgs e)
    {
        telemetry.Dispose();
        trayIcon.Visible = false;
        Application.Exit();
    }
}
