using KarleyLibrary.Erweiterungen;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using Microsoft.JSInterop;
using Serilog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WK5.Core;
using WK5.Core.Basis.Erweiterungen;
using WK5.Core.Models;
using WK5.Core.Services;

namespace WK5_Blazor.Components
{
    public partial class NotificationControl
    {




        private const int MaxShow = 5;
        public bool ShowAll { get; set; } = false;

#nullable disable        
        [CascadingParameter] public AppMitarbeiter Mitarbeiter { get; set; }
#nullable enable

        public async Task OnAllShown()
        {
            ShowAll = true;
            await InvokeAsync(StateHasChanged);
        }

        public async Task OnAllHide()
        {
            ShowAll = false;
            await InvokeAsync(StateHasChanged);
        }


        protected override async Task OnParametersSetAsync()
        {
            notificationService.NotificationsChanged += async (sender, e) =>
            {
                await PrepareDisplay();
            };

            await PrepareDisplay();
        }

        public IEnumerable<Notification> AllNotifications { get; set; } = Enumerable.Empty<Notification>();
        public IEnumerable<Notification> DisplayNotifications { get; set; } = Enumerable.Empty<Notification>();
        private async Task PrepareDisplay()
        {
            AllNotifications = notificationService.GetUserNotification(Mitarbeiter);

            if (AllNotifications.Count() < MaxShow || ShowAll)
            {
                DisplayNotifications = AllNotifications.Select(x => x);
            }
            else
            {
                DisplayNotifications = AllNotifications.OrderByDescending(x => x.NOTI_D_DATE).Take(MaxShow);
            }

            DisplayNotifications = DisplayNotifications.OrderByDescending(x => x.NOTI_D_DATE);

            await InvokeAsync(StateHasChanged);
        }

        private async Task HandleAlertClick(Notification notification)
        {
            if (!String.IsNullOrWhiteSpace(notification.NOTI_A_LINK))
            {
                await JSRuntime.OpenNewTab(notification.NOTI_A_LINK);
            }
            await InvokeAsync(StateHasChanged);
        }

        private async Task HandleAlertDelete(Notification notification)
        {
            using FbController2 fbController = new FbController2();
            await notificationService.RemoveNotification(notification);
            await InvokeAsync(StateHasChanged);
        }

        private async Task ToggleShowAll()
        {
            ShowAll = !ShowAll;
            await PrepareDisplay();
        }
    }
}
