// <copyright file="ProgressablePartitionReporting.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

#pragma warning disable SA1309 // Variables should not begin with underscore
#pragma warning disable SA1600 // Elements should be documented

namespace Jellyfin.Database.Implementations;

using System;
using System.Diagnostics;
using System.Linq;

/// <summary>
/// Wrapper for progress reporting on Partition helpers.
/// </summary>
/// <typeparam name="TEntity">The entity to load.</typeparam>
public class ProgressablePartitionReporting<TEntity>
{
    private readonly IOrderedQueryable<TEntity> _source;

    private readonly Stopwatch _partitionTime = new();

    private readonly Stopwatch _itemTime = new();

    internal ProgressablePartitionReporting(IOrderedQueryable<TEntity> source)
    {
        this._source = source;
    }

    internal Action<TEntity, int, int>? OnBeginItem { get; set; }

    internal Action<int>? OnBeginPartition { get; set; }

    internal Action<TEntity, int, int, TimeSpan>? OnEndItem { get; set; }

    internal Action<int, TimeSpan>? OnEndPartition { get; set; }

    internal IOrderedQueryable<TEntity> Source => this._source;

    internal void BeginItem(TEntity entity, int iteration, int itemIndex)
    {
        this._itemTime.Restart();
        this.OnBeginItem?.Invoke(entity, iteration, itemIndex);
    }

    internal void BeginPartition(int iteration)
    {
        this._partitionTime.Restart();
        this.OnBeginPartition?.Invoke(iteration);
    }

    internal void EndItem(TEntity entity, int iteration, int itemIndex)
    {
        this.OnEndItem?.Invoke(entity, iteration, itemIndex, this._itemTime.Elapsed);
    }

    internal void EndPartition(int iteration)
    {
        this.OnEndPartition?.Invoke(iteration, this._partitionTime.Elapsed);
    }
}
