import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/purchase.dart';
import 'package:aitrainer_app/service/logging.dart';
import 'package:aitrainer_app/util/not_found_exception.dart';
import 'dart:convert';
import 'api.dart';

class PurchaseApi with Logging {
  final APIClient _client = new APIClient();

  Future<List<Purchase>> getPurchasesByCustomer(int customerId) async {
    List<Purchase> purchases = [];
    try {
      final body = await _client.get("purchase/customer/" + customerId.toString(), "");
      final Iterable json = jsonDecode(body);
      final List<Purchase> purchases = json.map((purchase) => Purchase.fromJson(purchase)).toList();
      Cache().setPurchases(purchases);
    } on NotFoundException catch (_) {
      log("No purchases found");
    }
    return purchases;
  }

  Future<void> savePurchase(Purchase purchase) async {
    String body = JsonEncoder().convert(purchase.toJson());
    log(" ===== saving purchase:" + body);
    await _client.post("purchase/", body);
  }
}
