/**
 * Created by lx4r on 21.08.16.
 *
 * Storage of activities:
 * Object that contains a fresh ID and a map of the activities represented as an array:
 * {freshID: [...], activitiesArray: [...]}
 */
'use strict'

const fs = require('fs')
const config = require('./../configuration')

// Saves the loggedActivities into a JSON file
function saveActivities (activities) {
  fs.writeFile(config.readSettings('savefile-directory') + '/sheeptime-activities.json', JSON.stringify(activities), function (err) {
    if (err) {
      return console.log(err)
    }
    console.log('The file was saved!')
  })
}

// Returns an object with the saved activities and the fresh ID (see top)
function readActivities () {
  var activities = fs.readFileSync(config.readSettings('savefile-directory') + '/sheeptime-activities.json', 'utf8')
  if (activities) {
    return JSON.parse(activities)
  } else {
    return {freshID: 0, activitiesArray: []}
  }
}

module.exports = {
  saveActivities: saveActivities,
  readActivities: readActivities
}

@@ -277,16 +277,228 @@
 ration')
+%0Aconst activitiesFileName = 'sheeptime-activities.json'%0Aconst activitiesFilePath = config.readSettings('savefile-directory') + '/' + activitiesFileName%0Aconst defaultFileContent = %7BfreshID: 0, activitiesArray: %5B%5D%7D
 %0A%0A// Sav
@@ -596,80 +596,26 @@
 ile(
-config.readSettings('savefile-directory') + '/sheeptime-activities.json'
+activitiesFilePath
 , JS
@@ -712,47 +712,8 @@
   %7D%0A
-    console.log('The file was saved!')%0A
   %7D)
@@ -825,113 +825,123 @@
 %7B%0A  
-var activities = fs.readFileSync(config.readSettings('savefile-directory') + '/sheeptime-activities.json'
+if (fs.existsSync(activitiesFilePath)) %7B%0A    // file exists%0A    var activities = fs.readFileSync(activitiesFilePath
 , 'u
@@ -946,16 +946,18 @@
 'utf8')%0A
+  
   if (ac
@@ -964,24 +964,26 @@
 tivities) %7B%0A
+  
     return J
@@ -1004,16 +1004,18 @@
 vities)%0A
+  
   %7D else
@@ -1025,48 +1025,273 @@
     
-return %7BfreshID: 0, activitiesArray: %5B%5D%7D
+  // file exists but is empty%0A      return defaultFileContent%0A    %7D%0A  %7D else %7B%0A    // file doesn't exist -%3E create file and fill it with the default content%0A    fs.writeFileSync(activitiesFilePath, JSON.stringify(defaultFileContent));%0A    return defaultFileContent;
 %0A  %7D

create activities storage file if it doesn't exist