using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using BluetoothClientWP8.Resources;
using Windows.Networking.Sockets;
using Windows.Networking.Proximity;
using System.Diagnostics;
using Windows.Storage.Streams;
using System.Threading.Tasks;
using BluetoothConnectionManager;
using System.Windows.Media;
using Microsoft.Phone.UserData;

namespace BluetoothClientWP8
{
    public partial class MainPage : PhoneApplicationPage
    {
        private ConnectionManager connectionManager;
        private string resultA;
        private string resultB;
        private string resultC;
        private string resultD;
        private StateManager stateManager;
        private int mensag = 0;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            connectionManager = new ConnectionManager();
            connectionManager.MessageReceived += connectionManager_MessageReceived;
            stateManager = new StateManager();

        }

        async private void connectionManager_MessageReceived(string message)
        {
            Debug.WriteLine("Message received:" + message);
            string[] messageArray = message.Split(':');
            string data;
            
            int valor;

            if (mensag == 0)
            {
                data = String.Concat("N", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                await connectionManager.SendCommand(data);
                await connectionManager.SendCommand(resultA);
                await connectionManager.SendCommand(resultB);
                await connectionManager.SendCommand(resultC);
                await connectionManager.SendCommand(resultD);
                mensag = 1;
            }

             switch (messageArray[0])
            {
                case "BUSSOLA":
                    string ANGULO = messageArray[1].ToString();
                    string[] angulo = ANGULO.Split('.');
                    Dispatcher.BeginInvoke(delegate()
                    {
                        BodyDetectionStatus.Text = ANGULO;
                        int.TryParse(angulo[0], out valor);
                        imagem.RenderTransform = new RotateTransform() { CenterX = 0, CenterY = 0, Angle = (valor) };
                        //string vel = ":" + velocidade.Value.ToString() + ":" + direcao.Value.ToString();
                        //connectionManager.SendCommand(vel);
                    });

                break;
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            connectionManager.Initialize();
            stateManager.Initialize();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            connectionManager.Terminate();
        }

        private void ConnectAppToDeviceButton_Click_1(object sender, RoutedEventArgs e)
        {
            Appointments appts = new Appointments();

            //Identify the method that runs after the asynchronous search completes.
            appts.SearchCompleted += new EventHandler<AppointmentsSearchEventArgs>(Appointments_SearchCompleted);

            DateTime start = DateTime.Now;
            DateTime end = start.AddDays(5);
            int max = 20;

            //Start the asynchronous search.
            appts.SearchAsync(start, end, max, "Appointments Test #1");
            AppToDevice();
        }

        void Appointments_SearchCompleted(object sender, AppointmentsSearchEventArgs e)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            string dia;
            string mes;
            string ano;
            string hora;
            string minuto;

            foreach (Appointment appt in e.Results)
            {
                if (appt.IsAllDayEvent == false)
                {
                    if ((appt.StartTime.Hour == 0) && (appt.StartTime.Minute == 0) && (appt.StartTime.Second == 0))
                    {
                        //do nothing
                    }
                    else
                    {
                        if (appt.StartTime.Day < 10) dia = String.Concat("0", appt.StartTime.Day.ToString());
                        else dia = appt.StartTime.Day.ToString();
                        if (appt.StartTime.Month < 10) mes = String.Concat("0", appt.StartTime.Month.ToString());
                        else mes = appt.StartTime.Month.ToString();
                        ano = appt.StartTime.Year.ToString();
                        if (appt.StartTime.Hour < 10) hora = String.Concat("0", appt.StartTime.Hour.ToString());
                        else hora = appt.StartTime.Hour.ToString();
                        if (appt.StartTime.Minute < 10) minuto = String.Concat("0", appt.StartTime.Minute.ToString());
                        else minuto = appt.StartTime.Minute.ToString();

                        sb.AppendLine(String.Concat(dia,"/", mes, " - ", hora, ":", minuto, appt.Subject));
                    }

                }
            }
            
            var result = sb.ToString().Split(new[] { '\n' });

            try
            {
                resultA = String.Concat("A", result[0]);
            }
            catch
            {
                resultA = String.Concat("A", "00/00 - 00:00Nenhum Evento");
            }
            try
            {
                resultB = String.Concat("B", result[1]);
            }
            catch
            {
                resultB = String.Concat("B", "00/00 - 00:00Nenhum Evento");
            }
            try
            {
                resultC = String.Concat("C", result[2]);
            }
            catch
            {
                resultC = String.Concat("C","00/00 - 00:00Nenhum Evento");
            } 
            try
            {
                resultD = String.Concat("D", result[3]);
            }
            catch
            {
                resultD = String.Concat("D", "00/00 - 00:00Nenhum Evento");
            }
          
            //MessageBox.Show(resultB);
            
        }

        private static string DeleteLines(string input)
        {
            var result = input;
            var idx = result.IndexOf('\n');
            if (idx < 0)
            {
                // do what you want when there are less than the required lines
                return string.Empty;
            }
            result = result.Substring(idx + 1);
            return result;
        }

        private async void AppToDevice()
        {
            
            ConnectAppToDeviceButton.Content = "Connecting...";
            PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
            var pairedDevices = await PeerFinder.FindAllPeersAsync();

            if (pairedDevices.Count == 0)
            {
                Debug.WriteLine("No paired devices were found.");
            }
            else
            { 
                foreach (var pairedDevice in pairedDevices)
                {
                    if (pairedDevice.DisplayName == DeviceName.Text)
                    {
                        connectionManager.Connect(pairedDevice.HostName);
                        ConnectAppToDeviceButton.Content = "Connected";

                        DeviceName.IsReadOnly = true;
                        ConnectAppToDeviceButton.IsEnabled = false;
                        continue;

                    }
                }
            }

        }
    }
}