import 'package:aitrainer_app/model/customer_exercise_device.dart';
import 'package:aitrainer_app/service/logging.dart';
import 'package:aitrainer_app/util/not_found_exception.dart';
import 'dart:convert';

import 'api.dart';

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

  Future<List<CustomerExerciseDevice>> getDevices(int customerId) async {
    List<CustomerExerciseDevice> devices = [];
    try {
      log(" --- get customer_exercise_devices: ");
      final body = await _client.get("customer_exercise_device/customer/" + customerId.toString(), "");
      final Iterable json = jsonDecode(body);
      devices = json.map((device) => CustomerExerciseDevice.fromJson(device)).toList();
    } on NotFoundException catch (_) {
      log("No devices found");
      devices = [];
    }
    return devices;
  }

  Future<CustomerExerciseDevice> addDevice(CustomerExerciseDevice device) async {
    CustomerExerciseDevice savedDevice;
    try {
      final String body = JsonEncoder().convert(device.toJson());
      log(" --- add customer_exercise_device: " + body);
      final String responseBody = await _client.post("customer_exercise_device", body);
      savedDevice = CustomerExerciseDevice.fromJson(jsonDecode(responseBody));
    } on Exception catch (e) {
      throw new Exception(e.toString());
    }
    return savedDevice;
  }

  Future<void> removeDevice(int id) async {
    try {
      log(" --- delete customer_exercise_device: " + id.toString());
      await _client.post("customer_exercise_device/delete/" + id.toString(), "");
    } on Exception catch (e) {
      throw new Exception(e.toString());
    }
    return;
  }
}
