package ca.antonious.habittracker.habitstorage;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ca.antonious.habittracker.Constants;
import ca.antonious.habittracker.fileacess.IFileHandler;
import ca.antonious.habittracker.utils.StringUtils;
import ca.antonious.habittracker.models.Habit;

/**
 * Created by George on 2016-09-01.
 */
public class LocalHabitService implements IHabitService {
    private IFileHandler fileHandler;

    public LocalHabitService(IFileHandler fileHandler) {
        this.fileHandler = fileHandler;
    }

    @Override
    public List<Habit> getHabits() {
        return new ArrayList<>(loadHabits().values());
    }

    @Override
    public void addHabit(Habit habit) {
        Map<String, Habit> habits = loadHabits();
        habits.put(habit.getId(), habit);

        saveHabits(habits);
    }

    @Override
    public void updateHabit(Habit habit) {
        Map<String, Habit> habits = loadHabits();
        habits.put(habit.getId(), habit);

        saveHabits(habits);
    }

    @Override
    public void removeHabit(String id) {
        Map<String, Habit> habits = loadHabits();
        habits.remove(id);

        saveHabits(habits);
    }

    private Map<String, Habit> loadHabits() {
        String serializedHabits = fileHandler.loadFileAsString(Constants.HABIT_MAP_FILE_NAME);

        if (StringUtils.isStringNullOrEmpty(serializedHabits)) {
            return new HashMap<>();
        } else {
            return getGson().fromJson(serializedHabits, new TypeToken<Map<String, Habit>>() {}.getType());
        }
    }

    private void saveHabits(Map<String, Habit> habitMap) {
        String serializedHabits = getGson().toJson(habitMap);
        fileHandler.saveStringToFile(Constants.HABIT_MAP_FILE_NAME, serializedHabits);
    }

    private Gson getGson() {
        return new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").create();
    }
}

@@ -905,32 +905,87 @@
 = loadHabits();%0A
+%0A        if (!habits.containsKey(habit.getId())) %7B%0A    
         habits.p
@@ -1002,33 +1002,36 @@
 etId(), habit);%0A
-%0A
+    
         saveHabi
@@ -1034,32 +1034,42 @@
 Habits(habits);%0A
+        %7D%0A
     %7D%0A%0A    @Over
@@ -1158,32 +1158,86 @@
 = loadHabits();%0A
+%0A        if (habits.containsKey(habit.getId())) %7B%0A    
         habits.p
@@ -1262,17 +1262,20 @@
 habit);%0A
-%0A
+    
         
@@ -1286,32 +1286,42 @@
 Habits(habits);%0A
+        %7D%0A
     %7D%0A%0A    @Over
@@ -1412,24 +1412,67 @@
 adHabits();%0A
+%0A        if (habits.containsKey(id)) %7B%0A    
         habi
@@ -1486,17 +1486,20 @@
 ve(id);%0A
-%0A
+    
         
@@ -1510,32 +1510,42 @@
 Habits(habits);%0A
+        %7D%0A
     %7D%0A%0A    priva

Address failing LocalHabitServiceTests