import 'dart:convert';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/exercise_type.dart';
import 'package:aitrainer_app/service/api.dart';
import 'package:aitrainer_app/service/logging.dart';
import 'package:flutter/services.dart';

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

  Future<List<ExerciseType>> getExerciseTypes() async {
    final body = await _client.get("exercise_type", "");
    final Iterable json = jsonDecode(body);
    final List<ExerciseType> exerciseTypes = json.map((exerciseType) => ExerciseType.fromJson(exerciseType)).toList();

    await Future.forEach(exerciseTypes, (element) async {
      ExerciseType exerciseType = element as ExerciseType;
      exerciseType.imageUrl = await buildImage(exerciseType.imageUrl, exerciseType.exerciseTypeId);
    });
    log("ExerciseTypes downloaded");
    Cache().setExerciseTypes(exerciseTypes);

    return exerciseTypes;
  }

  Future<String> buildImage(String imageUrl, int exerciseTypeId) async {
    if (imageUrl.length > 8) {
      String assetImage = 'asset/menu/' + imageUrl.substring(7);
      return rootBundle.load(assetImage).then((value) {
        return assetImage;
      }).catchError((_) {
        String imagePath = assetImage.substring(10);
        String url = Cache.mediaUrl + 'images' + imagePath;
        return url;
      });
    } else {
      return imageUrl;
    }
  }
}
