import 'dart:convert';
import 'package:aitrainer_app/model/exercise.dart';
import 'package:aitrainer_app/service/api.dart';
import 'package:aitrainer_app/service/logging.dart';

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

  Future<void> saveExercise(Exercise exercise) async {
    String body = JsonEncoder().convert(exercise.toJson());
    log(" ===== saving exercise id: " + exercise.exerciseId.toString() + ":" + body);
    await _client.post("exercises/" + exercise.exerciseId.toString(), body);
  }

  Future<List<Exercise>> getExercisesByCustomer(int customerId) async {
    final body = await _client.get("exercises/customer/", customerId.toString());
    final Iterable json = jsonDecode(body);
    final List<Exercise> exercises = json.map((exercise) {
      Exercise item = Exercise.fromJson(exercise);
      return item;
    }).toList();
    //exercises.sort( (a, b) => b.dateAdd.compareTo(a.dateAdd) );

    return exercises;
  }

  Future<Exercise> addExercise(Exercise exercise) async {
    String body = JsonEncoder().convert(exercise.toJson());
    log(" ===== add new exercise: " + body);
    final String response = await _client.post("exercises", body);
    final Exercise savedExercise = Exercise.fromJson(jsonDecode(response));
    return savedExercise;
  }

  Future<void> deleteExercise(Exercise exercise) async {
    int exerciseId = exercise.exerciseId!;
    log(" ===== delete exercise: " + exerciseId.toString());
    await _client.post("exercises/" + exerciseId.toString(), "");
    return;
  }
}
