import 'dart:async';

import 'package:background_downloader/background_downloader.dart';
import 'package:flutter/foundation.dart';

class DownloaderService {
  static final Set<String> activeDownloads = {};
  late DownloadTask task;

  ValueNotifier<double> progressPer = ValueNotifier(0);
  ValueNotifier<TaskStatus?> onStatus = ValueNotifier(null);

  Future<String?> downloadFile(String url) async {
    if (activeDownloads.contains(url)) {
      return null;
    }

    activeDownloads.add(url);

    var fileName = url.split('/').last;
    if (!fileName.endsWith('.mp3')) {
      fileName = '$fileName.mp3';
    }
    task = DownloadTask(
      url: url,
      filename: fileName,
      updates: Updates.statusAndProgress,
      requiresWiFi: false,
      retries: 5,
      allowPause: true,
    );

    await FileDownloader().download(
      task,
      onProgress: (progress) {
        progressPer.value = progress;
      },
      onStatus: (status) {
        onStatus.value = status;
      },
    );
    activeDownloads.remove(url);
    return (await task.filePath());
  }

  pauseDownload() async {
    await FileDownloader().pause(task);
  }

  cancelDownload() async {
    await FileDownloader().cancelTaskWithId(task.taskId).whenComplete(() {
      progressPer.value = 0;
    });
  }

  resumeDownload() async {
    await FileDownloader().resume(task);
  }
}
