import 'dart:io';

import 'package:didvan/models/enums.dart';
import 'package:didvan/providers/core.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/storage/storage.dart';

class MediaProvider extends CoreProvier {
  static final List<int> downloadedItemIds = [];
  final List<String> downloadQueue = [];

  Future<void> getDownloadsList() async {
    downloadedItemIds.clear();
    final videosDir = Directory(
      StorageService.appDocsDir + ('/videos'),
    );
    final podcastsDir = Directory(
      StorageService.appDocsDir + ('/podcasts'),
    );
    if (!await videosDir.exists()) {
      await videosDir.create();
    }
    if (!await podcastsDir.exists()) {
      await podcastsDir.create();
    }
    videosDir.list(recursive: false).listen(
      (event) {
        downloadedItemIds.add(
          int.parse(
            event.path.split('/').last.split('-').last.split('.').first,
          ),
        );
      },
    );
    podcastsDir.list(recursive: false).listen(
      (event) {
        downloadedItemIds.add(
          int.parse(
            event.path.split('/').last.split('-').last.split('.').first,
          ),
        );
      },
    );
    await Future.delayed(const Duration(milliseconds: 300), notifyListeners);
  }

  Future<void> download({
    required String url,
    required String fileName,
    required bool isVideo,
  }) async {
    appState = AppState.busy;
    downloadQueue.add(url);
    notifyListeners();
    final service = RequestService(url);
    await service.download(fileName, isVideo ? 'videos' : 'podcasts');
    downloadQueue.remove(url);
    getDownloadsList();
  }
}
