using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Info;
using Microsoft.Phone.Shell;
using System;

namespace ScheduledTaskAgentImplementation
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            // Toast-Benachrichtigung initialisieren
            ShellToast myShellToast = new ShellToast();

            // Taskarten unterscheiden
            if (task is PeriodicTask)
            {
                // Periodic Task wird ausgefuehrt
                myShellToast.Title = "Periodic Task";
                myShellToast.Content = "FW: " + DeviceStatus.DeviceFirmwareVersion + " HW: " + DeviceStatus.DeviceHardwareVersion;
            }
            else
            {
                // Resource Intensive Task wird ausgefuehrt
                myShellToast.Title = "Resource Intensive Task";
                myShellToast.Content = "Speicher: " + DeviceStatus.ApplicationPeakMemoryUsage + " / " + DeviceStatus.ApplicationMemoryUsageLimit;
            }

            // Toast-Benachrichtigung anzeigen
            myShellToast.Show();

#if(DEBUG)
                ScheduledActionService.LaunchForTest("Mein PeriodicTask", TimeSpan.FromSeconds(10));
#endif

            NotifyComplete();
        }
    }
}