using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace UWPClient
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            InitializeComponent();
            Received += AppendLine;
        }

        public event Action<string> Received;

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.InvokeIfRequired(() => textBox.Text = "");
            Task.Run(() => StartClient());
        }

        private void AppendLine(string line)
        {
            this.InvokeIfRequired(() => {
                StringBuilder stringBuilder = new StringBuilder(textBox.Text);
                stringBuilder.AppendLine(line);
                textBox.Text = stringBuilder.ToString();
            });
        }

        private void StartClient()
        {
            try
            {
                using (TcpClient client = new TcpClient("localhost", 8000))
                using (Stream stream = client.GetStream())
                using (StreamReader reader = new StreamReader(stream))
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    string line;
                    writer.WriteLine();

                    while ((line = reader.ReadLine()) != null)
                    {
                        Received.Invoke(line);
                    }
                }
            }
            catch (Exception e)
            {
                textBox.Text = e.ToString();
            }
        }
    }
}