// Copyright (c) Microsoft Corporation. All rights reserved.



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Windows.Storage;

using System.Diagnostics;



// Needed for the DeviceWatcherTrigger

using Windows.ApplicationModel.Background;

using Windows.Devices.Enumeration;

using Windows.UI.Notifications;

using Windows.Data.Xml.Dom;

using Windows.Devices.Bluetooth;

using Windows.System.Threading;



namespace Tasks

{

    public sealed class BackgroundDeviceWatcher : IBackgroundTask

    {

        private ThreadPoolTimer _periodicTimer = null;

        private BackgroundTaskDeferral _deferral = null;

        private bool _cancelRequested = false;

        string template = $@"

                            <toast>

                            <visual>

                            <binding template=""ToastGeneric"">

                            </binding>

                            </visual>

                            </toast>

                            ";



        public async void Run(IBackgroundTaskInstance taskInstance)

        {

            _deferral = taskInstance.GetDeferral();



            var settings = ApplicationData.Current.LocalSettings;



            DeviceWatcherTriggerDetails triggerDetails = (DeviceWatcherTriggerDetails)taskInstance.TriggerDetails;



            foreach (DeviceWatcherEvent e in triggerDetails.DeviceWatcherEvents)

            {

                switch (e.Kind)

                {

                    case DeviceWatcherEventKind.Add:

                        {

                            Object value = settings.Values["readerAvailable"];

                            if (value != null && (bool)value == true)

                            {

                                PopToast(e.DeviceInformation.Name, "Available");

                            }

                        }

                        break;



                    case DeviceWatcherEventKind.Update:

                        try

                        {

                            Object value = settings.Values["readerConnection"];

                            if (value != null && (bool)value == true)

                            {

                                bool IsConnected = (bool)e.DeviceInformationUpdate.Properties["System.Devices.Aep.IsConnected"] == true;

                                BluetoothDevice device = await BluetoothDevice.FromIdAsync(e.DeviceInformationUpdate.Id);

                                PopToast(device.Name, IsConnected ? "Connected" : "Disconnected");

                            }

                        }

                        catch (Exception) { }

                        break;



                    case DeviceWatcherEventKind.Remove:

                        {

                            Object value = settings.Values["readerAvailable"];

                            if (value != null && (bool)value == true)

                            {

                                PopToast(e.DeviceInformationUpdate.Id, "Dissapeared");

                            }

                        }

                        break;

                }

            };



            //if (_periodicTimer == null)

            //    _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(60));



            _deferral.Complete();

        }



        private void PopToast(string name, string v)

        {

            ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;

            Object value = settings.Values["isApplicationWindowActive"];

            if (value != null)

            {

                bool isForeGround = (bool)value;

                if (!isForeGround)

                {

                    XmlDocument xml = new XmlDocument();

                    xml.LoadXml(template);

                    var binding = xml.SelectSingleNode("//binding");



                    var el = xml.CreateElement("text");

                    el.InnerText = name;



                    binding.AppendChild(el);



                    el = xml.CreateElement("text");

                    el.InnerText = v;

                    binding.AppendChild(el);

                    var toast = new ToastNotification(xml);

                    ToastNotificationManager.CreateToastNotifier().Show(toast);

                }

            }

        }



        //

        // Handles background task cancellation.

        //

        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)

        {

            //

            // Indicate that the background task is canceled.

            //

            _cancelRequested = true;

        }



        //

        // Simulate the background task activity.

        //

        private void PeriodicTimerCallback(ThreadPoolTimer timer)

        {

            if (_cancelRequested == false)

            {

                var settings = ApplicationData.Current.LocalSettings;

                Object value = settings.Values["readerBatteryStatus"];

                if (value != null && (bool)value == true)

                {

                    string status = (string)settings.Values["Battery Notification"];

                    if (status != null)

                    {

                        PopToast("BatteryNotification", status);

                        settings.Values.Remove("Battery Notification");

                    }

                }

            }

            else

            {

                _periodicTimer.Cancel();

                _deferral.Complete();

            }

        }

    }

}

