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

import 'api.dart';

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

  Future<List<CustomerExerciseDevice>> getDevices(int customerId) async {
    List<CustomerExerciseDevice> devices;
    try {
      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 (e) {
      print("No devices found");
    }
    return devices;
  }

  Future<CustomerExerciseDevice> addDevice(CustomerExerciseDevice device) async {
    CustomerExerciseDevice savedDevice;
    try {
      final String body = JsonEncoder().convert(device.toJson());
      print(" --- 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 {
      print(" --- 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;
  }
}