import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:mnemo_cards_common/mnemo_cards_common.dart';

import '../../managers/repository/api.dart';

class PacksApi with Api {
  final Dio _dio;

  PacksApi(this._dio);

  // previews for the main page
  Future<List<CardPackPreviewDto>> getPacksPreviews(
    Map<String, String?>? packData,
  ) async {
    final r = await _dio.get(
      '$path/packs/previews',
      queryParameters: packData,
    );
    final previews =
        (r.data! as String).decodeList(CardPackPreviewDto.fromJson).toList();
    return previews;
  }

  // previews for the main page
  Future<List<CardPackAction>> getPacksActions(
    Map<String, String?>? packData,
  ) async {
    final r = await _dio.get(
      '$path/packs/actions',
      queryParameters: packData,
    );
    final actions = (r.data! as String).decodeList(CardPackAction.fromJson);
    return actions;
  }

  // pack dto for available packs or null
  Future<CardPackDto?> getPackDto(String id) async {
    final r = await _dio.get<String>(
      '$path/pack/$id',
      options: Options(
        sendTimeout: Duration(seconds: 5),
        receiveTimeout: Duration(seconds: 5),
      ),
    );
    return (r.data as String).decode(CardPackDto.fromJson);
  }

  // buy page dto if not available
  Future<CardPackBuyDto?> getPackBuy(String id) async {
    final r = await _dio.get<String>(
      '$path/pack/buy/$id',
      options: Options(
        sendTimeout: Duration(seconds: 5),
        receiveTimeout: Duration(seconds: 5),
      ),
    );
    return (r.data as String).decode(CardPackBuyDto.fromJson);
  }

  /// cards zip archive for available pack
  /// unavailable packs transfer images by base64
  Future<Uint8List> packImagesArchive(String packId) async {
    final response = await _dio.get<Uint8List>(
      '$path/pack/cards/$packId',
      options: Options(
        responseType: ResponseType.bytes,
      ),
    );
    final data = response.data;
    if (data == null) {
      return Uint8List.fromList([]);
    }
    return data;
  }
}
