import 'dart:convert';
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 = (jsonDecode(r.data!) as List<dynamic>)
        .cast<Map<String, dynamic>>()
        .map(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 = (jsonDecode(r.data!) as List<dynamic>)
        .cast<Map<String, Object?>>()
        .map(CardPackAction.fromJson)
        .toList();
    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 CardPackDto.fromJson(
      jsonDecode(r.data as String) as Map<String, Object?>,
    );
  }

  // 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 CardPackBuyDto.fromJson(
      jsonDecode(r.data as String) as Map<String, Object?>,
    );
  }

  /// 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;
  }
}
