﻿using FiapTodoApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;

namespace FiapTodoApp.Services
{
    public static class NotificationService
    {
        public static int CreateScheduledToastNotification(TodoItem todoItem)
        {
            var toastId = (int)Math.Floor(new Random().NextDouble() * 100000000);

            return CreateOrUpdateScheduledToastNotification(todoItem, toastId);
        }

        public static void UpdateScheduledToastNotification(TodoItem todoItem)
        {
            CreateOrUpdateScheduledToastNotification(todoItem, todoItem.Appointment.Id);
        }

        private static int CreateOrUpdateScheduledToastNotification(TodoItem todoItem, int toastId)
        {
            DeleteScheduledToastNotification(toastId);

            XmlDocument toastXml = new XmlDocument();

            string toastXmlString =
            $@"<toast scenario='alarm'>
            <visual>
                <binding template='ToastGeneric'>
                <text>{todoItem.Title}</text>
                <text>{todoItem.Details}</text>
                </binding>
            </visual>
        </toast>";

            toastXml.LoadXml(toastXmlString);

            var reminderTimeSpan = new TimeSpan(0, (int)Math.Floor(todoItem.Appointment.Reminder), 0);
            var toastTime = todoItem.StartDate.Value.Subtract(reminderTimeSpan);

            var toast = new ScheduledToastNotification(toastXml, toastTime);
            toast.Id = toastId.ToString();

            ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);

            return toastId;
        }

        public static void DeleteScheduledToastNotification(int toastId)
        {
            var notification = ToastNotificationManager.CreateToastNotifier()
                                    .GetScheduledToastNotifications().SingleOrDefault(n => n.Id == toastId.ToString());

            if (notification != null)
            {
                ToastNotificationManager.CreateToastNotifier().RemoveFromSchedule(notification);
            }
        }
    }

}
