using System.Net.Sockets;
using System.Windows;

namespace ITNexusAgent.UI;

public partial class RdpConsentWindow : Window
{
    private readonly int _port;
    private bool _answered = false;
    private System.Threading.CancellationTokenSource _countdownCts = new();

    public RdpConsentWindow(int port)
    {
        InitializeComponent();
        _port = port;
        _ = RunCountdownAsync(_countdownCts.Token);
    }

    private async Task RunCountdownAsync(System.Threading.CancellationToken ct)
    {
        for (int i = 30; i > 0; i--)
        {
            if (ct.IsCancellationRequested) return;
            Dispatcher.Invoke(() => CountdownText.Text = $"Automatische Ablehnung in {i} Sekunden");
            await Task.Delay(1000, ct).ContinueWith(_ => { });
        }
        if (!_answered)
        {
            SendResponse(false);
            Dispatcher.Invoke(Close);
        }
    }

    private void AcceptButton_Click(object sender, RoutedEventArgs e)
    {
        _countdownCts.Cancel();
        SendResponse(true);
        Close();
    }

    private void DenyButton_Click(object sender, RoutedEventArgs e)
    {
        _countdownCts.Cancel();
        SendResponse(false);
        Close();
    }

    private void SendResponse(bool accepted)
    {
        if (_answered) return;
        _answered = true;
        try
        {
            using var tcp = new TcpClient();
            tcp.Connect("127.0.0.1", _port);
            tcp.GetStream().WriteByte((byte)(accepted ? 1 : 0));
            tcp.GetStream().Flush();
        }
        catch { }
    }
}
