using System;
using System.Collections.Generic;
using System.Linq;
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 Quobject.SocketIoClientDotNet.Client;
using System.IO;
using System.Drawing;
using System.Windows.Threading;
using System.Globalization;
using Phidgets;
using Phidgets.Events;

namespace LDServer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Socket socket;
        private string filePath = "599LD.wav";
        System.Windows.Threading.DispatcherTimer Timer = new System.Windows.Threading.DispatcherTimer();
        InterfaceKit ik = new InterfaceKit();
        private bool alarmOn = false;
        System.Media.SoundPlayer alarmPlayer = new System.Media.SoundPlayer("alarm.wav");

        public MainWindow()
        {
            InitializeComponent();
            this.WindowStyle = System.Windows.WindowStyle.None;
            this.WindowState = System.Windows.WindowState.Maximized;

            ik.Attach += ik_Attach;
            ik.open();

            Timer.Tick += new EventHandler(Timer_Click);
            Timer.Interval = new TimeSpan(0, 0, 1);
            Timer.Start();

            socket = IO.Socket("http://162.246.156.14:1337");
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                socket.Emit("hi", "testing");
            });

            socket.On("voiceMessageFromServer", (data) =>
            {
                try
                {
                    Console.WriteLine("Voice message received.");
                    byte[] bytes = System.Convert.FromBase64String(data.ToString());
                    File.WriteAllBytes(@filePath, bytes);
                    ik.outputs[0] = true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error trying to update voice message or turn on light: " + ex.Message);
                }                
            });

            socket.On("updatePhoto", (data) =>
            {
                Console.WriteLine("Photo received.");
                try
                {
                    var bytes = new Byte[0];
                    using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(data.ToString())))
                    {
                        var bitmap = new BitmapImage();
                        bitmap.BeginInit();
                        bitmap.StreamSource = ms;
                        bitmap.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                        bitmap.CacheOption = BitmapCacheOption.OnLoad;
                        bitmap.EndInit();
                        bitmap.Freeze();

                        ImageSource imageSource = bitmap;
                        Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
                        {
                            imgPhoto.Source = imageSource;
                        }));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error trying to update photo: " + ex.Message);
                }
            });

            socket.On("alarmOn", (data) =>
            {
                Console.WriteLine("Alarm turned on remotely.");
                playAlarm();
                alarmOn = true;
                ik.outputs[0] = true;
            });
        }

        void ik_Attach(object sender, AttachEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(delegate()
            {
                Console.WriteLine("IK attached");

                ik.Detach += ik_Detach;
                ik.Error += ik_Error;
                ik.InputChange += ik_InputChange;
            }));
        }

        void ik_Error(object sender, Phidgets.Events.ErrorEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(delegate()
            {
                Console.WriteLine("IK Error: " + e.Description);
            }));
        }

        void ik_Detach(object sender, DetachEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(delegate()
            {
                ik.Detach -= ik_Detach;
                ik.Error -= ik_Error;

                //set the TB text box to reflect that the interfacekit is detached
                Console.WriteLine("IK detached");
            }));
        }

        void ik_InputChange(object sender, InputChangeEventArgs e)
        {
            if (ik.inputs[0])
            {
                Console.WriteLine("Button pressed");
                if (alarmOn)
                {
                    alarmOn = false;
                    ik.outputs[0] = false;
                    alarmPlayer.Stop();
                }
                else
                {
                    playRecording();
                }
                ik.outputs[0] = false;
            }
            else
            {
                Console.WriteLine("Button released");
            }
        }
        private void playRecording()
        {
            try
            {
                System.Media.SoundPlayer player = new System.Media.SoundPlayer(@filePath);
                player.Play();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to play sound file: " + ex.Message);
            }
        }
        private void playAlarm()
        {
            try
            {
                alarmPlayer.PlayLooping();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to play alarm: " + ex.Message);
            }
        }

        private void Timer_Click(object sender, EventArgs e)
        {
            DateTime d;
            d = DateTime.Now;
            lblClock.Content = d.ToString("hh:mm", CultureInfo.InvariantCulture);
        }
    }
}
