using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Media.Animation;

namespace ITNexusAgent.UI;

public partial class RdpActiveIndicatorWindow : Window
{
    private readonly int _port;
    private readonly string _secret;
    private readonly DateTime _startedAt = DateTime.Now;
    private readonly System.Windows.Threading.DispatcherTimer _timer = new();
    private bool _signaled = false;

    public RdpActiveIndicatorWindow(int port, string secret)
    {
        InitializeComponent();
        _port = port;
        _secret = secret;

        Loaded += (s, e) =>
        {
            var area = SystemParameters.WorkArea;
            Left = area.Right - Width - 16;
            Top = area.Bottom - Height - 16;
            ((Storyboard)Resources["PulseAnim"]).Begin(PulseDot);
        };

        _timer.Interval = TimeSpan.FromSeconds(1);
        _timer.Tick += (s, e) =>
        {
            var elapsed = DateTime.Now - _startedAt;
            DurationText.Text = $"IT-Abteilung sieht zu · {elapsed:mm\\:ss}";
        };
        _timer.Start();
    }

    private void DisconnectButton_Click(object sender, RoutedEventArgs e)
    {
        SendDisconnectSignal();
        Close();
    }

    private void SendDisconnectSignal()
    {
        if (_signaled) return;
        _signaled = true;
        try
        {
            using var tcp = new TcpClient();
            tcp.Connect("127.0.0.1", _port);
            var stream = tcp.GetStream();
            stream.Write(Encoding.ASCII.GetBytes(_secret));
            stream.WriteByte(1);
            stream.Flush();
        }
        catch { }
    }
}
