﻿//using Microsoft.Kinect;
using CubeMaster2000.CubeApps;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace CubeMaster2000
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //

        private AppBase _runningApp;
        private bool _udpConfigPending = true;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
        }

        public void LogMessage(string message)
        {
            textBoxLog.AppendText(string.Concat(message, "\n"));
        }
        
        private void buttonStart_Click(object sender, RoutedEventArgs e)
        {
            if (_runningApp != null)
            {
                _runningApp.Dispose();
                _runningApp.ImageChanged -= ImageChanged;
                _runningApp = null;
            }

            if (radioButtonModeLine.IsChecked == true)
                _runningApp = new TestImage();
            else if (radioButtonModeSkeleton.IsChecked == true)
                _runningApp = new SkeletonImage();
            else if (radioButtonModeAnimation.IsChecked == true)
                _runningApp = new TestAnimation();
            //else if (radioButtonModeSnake.IsChecked == true)
            //    _runningApp = new Snake(8, this);
            else if (radioButtonModeKinect.IsChecked == true)
                _runningApp = new KinectStickman(8, this);
            else if (radioButtonModeClear.IsChecked == true)
                _runningApp = new ClearImage();

            if (_runningApp == null) return;

            _runningApp.ImageChanged += new AppBase.ImageChageHandler(ImageChanged);
            _runningApp.Start();
        }

        private void ImageChanged(CubeImage image)
        {
            SendImage(image);
        }

        //private List<UdpClient> _clients = null;
        private List<TcpClient> _clients = null;
        private List<IPEndPoint> _hosts = null;    
    

        private void SetupUdpClients()
        {
            LogMessage("Setup clients....");

            _hosts = new List<IPEndPoint>();
            
            if (checkBoxEnableHost1.IsChecked == true)
                _hosts.Add(new IPEndPoint(IPAddress.Parse(textBoxHost1.Text), Convert.ToInt32(textBoxPort1.Text)));

            if (checkBoxEnableHost2.IsChecked == true)
                _hosts.Add(new IPEndPoint(IPAddress.Parse(textBoxHost2.Text), Convert.ToInt32(textBoxPort2.Text)));

            if (checkBoxEnableHost3.IsChecked == true)
                _hosts.Add(new IPEndPoint(IPAddress.Parse(textBoxHost3.Text), Convert.ToInt32(textBoxPort3.Text)));

            /*
            if (_clients != null)
            {
                foreach (TcpClient c in _clients)
                    c.Close();
                _clients = null;
            }

            _clients = new List<TcpClient>();
            
            List<IPAddress> hosts = new List<IPAddress>();

            if (checkBoxEnableHost1.IsChecked == true) hosts.Add(IPAddress.Parse(textBoxHost1.Text));
            if (checkBoxEnableHost2.IsChecked == true) hosts.Add(IPAddress.Parse(textBoxHost2.Text));
            if (checkBoxEnableHost3.IsChecked == true) hosts.Add(IPAddress.Parse(textBoxHost3.Text));

            foreach (IPAddress address in hosts)
            {
                var client = new TcpClient();
                IPEndPoint ep = new IPEndPoint(address, 11000); // endpoint where server is listening
                client.Connect(ep);

                _clients.Add(client);
            }
            */
        }

        DateTime _lastReceived = DateTime.MinValue;

        private void SendImage(CubeImage image)
        {
            if ((DateTime.Now - _lastReceived).TotalMilliseconds < 250)
                return;

            if (_udpConfigPending)
            {
                SetupUdpClients();
                _udpConfigPending = false;
            }

            // send data
            byte[] dgram = image.ToPacket();

            foreach (IPEndPoint endpoint in _hosts)
            {
                var client = new TcpClient();
                
                client.Connect(endpoint);

                using (NetworkStream stream = client.GetStream())
                {
                    stream.Write(dgram, 0, dgram.Length);
                }

                client.Close();
            }

            /*
            foreach (TcpClient client in _clients)
            {

                
                using (NetworkStream stream = client.GetStream())
                {
                    stream.Write(dgram, 0, dgram.Length);
                }

                
                //client.Send(dgram, dgram.Length);
                //var receivedData = client.Receive(ref ep);
            }*/
            
        }

        private void textBoxHost_TextChanged(object sender, TextChangedEventArgs e)
        {
            _udpConfigPending = true;
        }

        private void checkBoxEnableHost_Click(object sender, RoutedEventArgs e)
        {
            _udpConfigPending = true;
        }
    }
}
