using Blazorise.DataGrid;
using FoodsharingSiegen.Contracts.Entity;
using FoodsharingSiegen.Contracts.Helper;
using FoodsharingSiegen.Server.Data.Service;
using Microsoft.AspNetCore.Components;

namespace FoodsharingSiegen.Server.Pages
{
    /// <summary>
    ///     The audit view class (a. beging, 23.05.2022)
    /// </summary>
    public partial class AuditView
    {
        #region Dependencies

        /// <summary>
        ///     Gets or sets the value of the audit service (ab)
        /// </summary>
        [Inject]
        public AuditService? AuditService { get; set; }

        #endregion

        #region Private Properties

        /// <summary>
        ///     Gets or sets the value of the audits (ab)
        /// </summary>
        private List<Audit>? Audits { get; set; }

        /// <summary>
        ///     Gets or sets the value of the total audits (ab)
        /// </summary>
        private int TotalAudits { get; set; }

        #endregion

        #region Override InitializeDataAsync

        /// <inheritdoc />
        protected override Task InitializeDataAsync()
        {
            if (!CurrentUser.IsAdmin()) NavigationManager.NavigateTo("/");
            return Task.CompletedTask;
        }

        #endregion

        #region Private Method OnReadData

        /// <summary>
        ///     Called when data is read (ab)
        /// </summary>
        /// <param name="e">The params</param>
        private async Task OnReadData(DataGridReadDataEventArgs<Audit> e)
        {
            if (!CurrentUser.IsAdmin()) return;

            var countLoad = await AuditService?.GetCount()!;
            if (countLoad.Success)
                TotalAudits = countLoad.Data;

            // Default fallback if VirtualizeCount is not set, though Blazor shouldn't do this usually
            var limit = e.VirtualizeCount > 0 ? e.VirtualizeCount : 50;
            var offset = e.VirtualizeOffset;

            var itemsLoad = await AuditService?.LoadPage(offset, limit)!;
            if (itemsLoad.Success)
                Audits = itemsLoad.Data;

            await InvokeAsync(StateHasChanged);
        }

        #endregion
    }
}