using System;
using System.Collections.Generic;
using System.Windows;

namespace TcpWindows
{
    using JacekMatulewski.Communication.Ntpp;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private NtppClient ntppClient;

        private static string[] getValidIPAddresses()
        {
            List<string> addresses = new List<string>();
            System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
            foreach (System.Net.IPAddress adres in host.AddressList)
                addresses.Add(adres.ToString());
            return addresses.ToArray();
        }

        private void pokażAdresyIp()
        {
            string[] addresses = getValidIPAddresses();
            string s = "Lokalne adresy IP:\r\n";
            foreach (string address in addresses)
                s += address + "\r\n";
            tbLokalneAdresyIp.Text = s.TrimEnd('\r','\n');
        }

        public MainWindow()
        {
            InitializeComponent();

            pokażAdresyIp();

            ntppClient = new NtppClient();
            ntppClient.StateChanged += ntppClient_StateChanged;
            ntppClient.TextReceived += ntppClient_TextReceived;
        }

        private void ntppClient_StateChanged(object sender, NtppClient.StateChangedEventArgs e)
        {
            Action a = () => { tbStan.Text = e.NewState.ToString(); };
            if (!Dispatcher.CheckAccess()) Dispatcher.Invoke(a); else a();
        }

        private void ntppClient_TextReceived(object sender, NtppClient.TextReceivedEventArgs e)
        {
            Action a = () => { lbOdebraneKomunikaty.Items.Add(e.ReceivedFrom.Hostname + " (" + DateTime.Now.ToString() + "): " + e.ReceivedText); };
            if (!Dispatcher.CheckAccess()) Dispatcher.Invoke(a); else a();
        }

        private void btnPolacz_Click(object sender, RoutedEventArgs e)
        {
            NtppConnectionData connectionData = new NtppConnectionData()
            {
                Hostname = tbAdres.Text,
                Port = Convert.ToInt32(tbPort.Text)
            };
            ntppClient.WaitForConnection(connectionData);
        }

        private void btnRozlacz_Click(object sender, RoutedEventArgs e)
        {
            ntppClient.Disconnect();
        }

        private void btnWyslij_Click(object sender, RoutedEventArgs e)
        {
            ntppClient.SendText(tbTekst.Text);
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            //to odłączanie zdarzeń to przejaw paranoi
            ntppClient.StateChanged -= ntppClient_StateChanged;
            ntppClient.TextReceived -= ntppClient_TextReceived;
            
            btnRozlacz_Click(this, null);
        }
    }
}
