package de.avalax.fitbuddy.port.adapter.service;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.util.List;

import de.avalax.fitbuddy.domain.model.exercise.BasicExercise;
import de.avalax.fitbuddy.domain.model.exercise.Exercise;
import de.avalax.fitbuddy.domain.model.set.Set;
import de.avalax.fitbuddy.domain.model.workout.BasicWorkout;
import de.avalax.fitbuddy.domain.model.workout.Workout;
import de.avalax.fitbuddy.domain.model.workout.WorkoutParseException;

public class JsonToWorkoutAdapter {
    private Gson gson = new Gson();

    public Workout createFromJson(String contents) throws WorkoutParseException {
        if (contents == null || contents.isEmpty()) {
            throw new WorkoutParseException();
        }
        try {
            List jsonWorkout = gson.fromJson(contents, List.class);
            List<List> jsonExercises = (List<List>) jsonWorkout.get(1);
            Workout workout = new BasicWorkout();
            workout.setName((String) jsonWorkout.get(0));

            for (List jsonExercise : jsonExercises) {
                Exercise exercise = new BasicExercise();
                exercise.setName((String) jsonExercise.get(0));

                List<List> jsonSets = (List<List>) jsonExercise.get(1);
                for (List jsonSet : jsonSets) {
                    double weight = (double) jsonSet.get(1);
                    int maxReps = (int) ((double) jsonSet.get(0));
                    Set set = exercise.createSet();
                    set.setWeight(weight);
                    set.setMaxReps(maxReps);
                }
                workout.getExercises().addExercise(workout.getExercises().countOfExercises(), exercise);
            }
            return workout;
        } catch (JsonSyntaxException re) {
            throw new WorkoutParseException(re);
        }
    }
}

@@ -1616,32 +1616,55 @@
 %0A               
+ int countOfExercises =
  workout.getExer
@@ -1675,19 +1675,23 @@
 s().
-add
+countOf
 Exercise
 (wor
@@ -1686,17 +1686,37 @@
 Exercise
-(
+s();%0A                
 workout.
@@ -1722,32 +1722,44 @@
 .getExercises().
+addExercise(
 countOfExercises
@@ -1758,18 +1758,16 @@
 xercises
-()
 , exerci

extract variable