var fs = require('fs');
var appRoot = require('app-root-path');
var timelineUtils = require('../utils/timeline-utils');

require('dotenv').load({path: appRoot + '/.env'});

var generateCommitsTimeline = function() {
    var db = require('../db/content-provider');
    db.loadDatabase({}, function() {
        var outputFilename = process.env.JSON_FILENAME + '.json';
        var commits = db.getCollection('commits');
        var githubCommits = timelineUtils.getCommitsPerDay(commits, 'github');
        var bitbucketCommits = timelineUtils.getCommitsPerDay(commits, 'bitbucket');
        var allCommits = githubCommits.concat(bitbucketCommits);

        var sortedCommitsByDate = allCommits.sort(function(first, second) {
            return new Date(first.date) - new Date(second.date);
        });

        var jsonData = sortedCommitsByDate.reduce(function(acc, item) {
            var currentDate = item.date;
            if (acc[currentDate] != null) {
                acc[currentDate] += item.num_commits;
            } else {
                acc[currentDate] = item.num_commits;
            }

            return acc;
        }, {});

        fs.writeFileSync(outputFilename, JSON.stringify(jsonData));
    });
}

module.exports = {
    generateCommitsTimeline: generateCommitsTimeline
};

@@ -205,24 +205,60 @@
 unction() %7B%0A
+    let afterDbLoaded = () =%3E %7B%0A    
     var db =
@@ -291,18 +291,30 @@
 ovider')
-;%0A
+.getDB();%0A    
     db.l
@@ -346,24 +346,28 @@
 ) %7B%0A        
+    
 var outputFi
@@ -412,16 +412,20 @@
 .json';%0A
+    
         
@@ -471,24 +471,28 @@
 ');%0A        
+    
 var githubCo
@@ -554,24 +554,28 @@
 ');%0A        
+   
+ 
 var bitbucke
@@ -643,24 +643,28 @@
 ');%0A        
+    
 var allCommi
@@ -713,24 +713,28 @@
 );%0A%0A        
+   
+ 
 var sortedCo
@@ -797,24 +797,28 @@
             
+    
 return new D
@@ -866,21 +866,29 @@
         
+   
+ 
 %7D);%0A%0A
+    
         
@@ -959,24 +959,28 @@
             
+   
+ 
 var currentD
@@ -996,16 +996,20 @@
 m.date;%0A
+    
         
@@ -1052,32 +1052,36 @@
                 
+   
+ 
 acc%5BcurrentDate%5D
@@ -1114,16 +1114,20 @@
         
+    
 %7D else %7B
@@ -1135,32 +1135,36 @@
                 
+   
+ 
 acc%5BcurrentDate%5D
@@ -1196,19 +1196,26 @@
         
-%7D%0A%0A
+    %7D%0A%0A   
         
@@ -1214,24 +1214,25 @@
             
+ 
 return acc;%0A
@@ -1239,16 +1239,20 @@
         
+    
 %7D, %7B%7D);%0A
@@ -1248,24 +1248,28 @@
    %7D, %7B%7D);%0A%0A
+    
         fs.w
@@ -1328,17 +1328,149 @@
 ));%0A    
-%7D
+    %7D);%0A    %7D;%0A%0A    const ContentProvider = require('../db/content-provider');%0A    ContentProvider.createOrLoadDatabase(afterDbLoaded
 );%0A%7D%0A%0Amo

refactor timeline-generator to make sure db is fully loaded before reading from it