import 'dart:typed_data';

import 'package:fis_vid/async_vid/cached/vid_data.dart';
import 'package:fis_vid/async_vid/http/vid_data.dart';
import 'package:fis_vid/async_vid/vid_data.dart';
import 'package:fis_vid/cache/io.dart';
import 'package:vid/us/vid_us_data_http_reader.dart';

import 'channel.dart';

class VidDataChannelImpl extends VidDataChannel {
  VidDataChannelImpl(String url) : super(url);

  static void receiveChunk(String id, Uint8List chunk) {}

  @override
  Future<AsyncVidImageDataBase> buildSource() async {
    final cacheBuffer = await VidNativeCache.ins.getCache(url);
    if (cacheBuffer != null) {
      return AsyncCachedVidImageData(
        cacheBuffer,
        downloadCallback: onDownloadCallback,
      );
    }
    return AsyncHttpVidImageData(
      url,
      downloadCallback: _onHttpDownloadCallback,
    );
  }

  void _onHttpDownloadCallback(double progress, DownloadErrorException? error) {
    if (progress >= 1) {
      final bytes = source!.getDownloadedData();
      VidNativeCache.ins.saveCache(url, bytes);
    }
    onDownloadCallback(progress, error);
  }
}