// Author: fengshengxiong
// Date: 2024/7/17
// Description: 下载队列

import 'dart:collection';

class DownloadQueueTask {
  int maxThread = 1;

  DownloadQueueTask(this.maxThread);

  ///当前任务队列
  final Queue<_TaskInfo> _queue = Queue();

  ///是否工作中
  int _taskCount = 0;

  void create(String taskName, Function(String name) workTask) {
    _queue.add(_TaskInfo(taskName, workTask));
    _exec();
  }

  void _exec() async {
    if (_taskCount >= maxThread) return;
    if (_queue.isEmpty) return;

    for (int i = 0; i < maxThread; i++) {
      if (_queue.isEmpty) continue;

      _TaskInfo taskInfo = _queue.removeFirst();
      _taskCount += 1;
      await taskInfo.workTask.call(taskInfo.taskName);
      _taskCount -= 1;
    }
    _exec();
  }
}

class _TaskInfo {
  String taskName;
  Function(String taskName) workTask;

  _TaskInfo(this.taskName, this.workTask);
}