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

import 'api.dart';

class CustomerExerciseDeviceApi with Logging {
  final APIClient _client = 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", "");
      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 = const 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 Exception(e.toString());
    }
    return savedDevice;
  }

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