
import 'dart:typed_data';

import 'package:archive/archive.dart';
import 'package:flutter/services.dart';

class AudioCache {

  // Filename, bytes
  Map<String, Uint8List> _audioCache = {};

  List<String> get keys {
    return _audioCache.keys.toList();
  }

  Uint8List operator [](String key) {
    return _audioCache[key]!;
  }
}

class AnnouncementCache extends AudioCache {

  String _assetLocation = "assets/ibus_recordings.zip";

  Future<void> loadAnnouncements(List<String> Announcements) async {

    final bytes = await rootBundle.load(_assetLocation);
    final archive = ZipDecoder().decodeBytes(bytes.buffer.asUint8List());

    for (final file in archive) {

      String filename = file.name;
      if (filename.contains("/")) {
        filename = filename.split("/").last;
      }

      if (Announcements.contains(filename)) {
        _audioCache[filename] = file.content;
        print("Loaded announcement: ${filename}");
      }
    }
  }

  Future<void> loadAllAnnouncements() async {

    print("Loading all announcements.");

    final bytes = await rootBundle.load(_assetLocation);
    final archive = ZipDecoder().decodeBytes(bytes.buffer.asUint8List());

    print("Done decoding zip file.");
    print("Number of files: ${archive.length}");

    for (final file in archive) {

      if (file.isFile == false) {
        continue;
      }

      String filename = file.name;
      if (filename.contains("/")) {
        filename = filename.split("/").last;
      }

      _audioCache[filename] = file.content;
    }

    print("Done loading all announcements.");
  }

}