using System;
using System.Threading;
using System.Threading.Tasks;

namespace PCL.Core.Utils.Threading;

// Partly generated by o4-mini-high (20250709)

/// <summary>
/// 可限制并发线程数量的任务池。
/// </summary>
public class LimitedTaskPool
{
    /// <summary>
    /// 最大并发线程数。
    /// </summary>
    public int MaxThread { get; }

    private readonly TaskFactory _factory;
    private readonly CancellationTokenSource _cts = new();

    /// <summary>
    /// 初始化 <see cref="LimitedTaskPool"/> 实例
    /// </summary>
    /// <param name="maxThread">参考 <see cref="MaxThread"/>，最小为 1</param>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="maxThread"/> 小于 1</exception>
    public LimitedTaskPool(int maxThread)
    {
        if (maxThread < 1) throw new ArgumentOutOfRangeException(nameof(maxThread));

        MaxThread = maxThread;

        var scheduler = new LimitedConcurrencyLevelTaskScheduler(maxThread);
        var cancellationToken = _cts.Token;

        _factory = new TaskFactory(
            cancellationToken,
            TaskCreationOptions.DenyChildAttach,
            TaskContinuationOptions.None,
            scheduler);
    }

    /// <summary>
    /// 提交一个任务。
    /// </summary>
    public Task Submit(Action work) => _factory.StartNew(work);

    /// <summary>
    /// 提交一个异步任务。
    /// </summary>
    public Task Submit(Func<Task> work) => _factory.StartNew(work).Unwrap();

    /// <summary>
    /// 取消所有任务。
    /// </summary>
    public void CancelAll() => _cts.Cancel();
}
