using Blazored.SessionStorage;
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using WK5.Core.Basis;


namespace WK5_Blazor.Pages
{
    public class AlertPageBase : HotKeyPageBase
    {
        protected List<AlertBox> ShowAlerts { get; set; } = new List<AlertBox>();

        private List<Timer> _timers { get; set; } = new List<Timer>();

#nullable disable
        [Inject] public ISessionStorageService SessionStorage { get; set; }
#nullable enable
        /// <summary>
        /// Ruft die Alerts aus dem SessionStorage ab und legt diese auf die Eigenschaft <see cref="ShowAlerts"/> fest.
        /// </summary>
        /// <returns></returns>
        protected async Task SetAlerts()
        {
            List<AlertBox>? alerts = await SessionStorage.GetItemAsync<List<AlertBox>>("alerts");

            if (alerts is not null)
            {
                ShowAlerts = alerts;
                await SessionStorage.ClearAsync();
            }
        }
        /// <summary>
        /// Fügt ein Alert dem SessionStorage hinzu, das beim nächsten Aufruf von <see cref="SetAlerts"/> abgerufen wird.
        /// </summary>
        /// <param name="alert"></param>
        /// <returns></returns>
        protected async Task AddAlertAsync(AlertBox alert)
        {
            List<AlertBox> alerts = (await SessionStorage.GetItemAsync<List<AlertBox>>("alerts")) ?? new List<AlertBox>();
            alerts.Add(alert);
            await SessionStorage.SetItemAsync("alerts", alerts);

            if (alert.DecayTime > 0 && alert.AlertType is AlertType.Success)
            {
                _timers.Add(new Timer(async (state) =>
                {
                    if (state is AlertBox box)
                    {
                        ShowAlerts.RemoveAll(x => x.Message.Equals(box.Message, StringComparison.OrdinalIgnoreCase));
                        await InvokeAsync(StateHasChanged);
                    }
                }, alert, alert.DecayTime * 1000, Timeout.Infinite));
            }
            await InvokeAsync(StateHasChanged);
        }

        protected async Task AddAlertsAsync(List<AlertBox> alerts)
        {
            foreach (var alert in alerts)
            {
                await AddAlertAsync(alert);
            }
        }
    }
}
