/**
 * Given a path to a `pelias/acceptance-tests` tests JSON file, add the tests
 * in the local Mongo server's Pelias collection (as stored by the feedback
 * app) to it.
 */

var fs = require( 'fs' );
var mongo = require( 'mongodb' );
var monk = require( 'monk' );
var db = monk( 'localhost:27017/pelias' );

function backupCollection( cb ){
  db.get( 'pelias' ).find({}, function (err, docs){
    db.get( 'peliasBackup' ).insert( docs, function (){
      peliasCollection.remove( {}, function (){
        db.close();
        cb();
      });
    });
  });
}

function addTests( oldTests, newDocs ){
  var existingInputs = oldTests.map( function ( test ){
    return test.in.input;
  });

  var timestamp = new Date().getTime().toString() + ':';
  var testCaseId = 0;
  newDocs.forEach( function ( doc ){
    if( existingInputs.indexOf( doc.query ) !== -1 ){
      return;
    }
    existingInputs.push( doc.query );
    var testCase = {
      id: timestamp + testCaseId++,
      user: 'feedback-app',
      in: {
        input: doc.query
      },
      expected: {
        properties: null
      }
    };

    if( doc.foundInPelias ){
      testCase.status = 'pass';
      testCase.expected.properties = doc.selected.map( function ( selectedItem ){
        delete selectedItem.properties.id;
        return selectedItem.properties;
      });
    }
    else if( 'selected' in doc && doc.selected.length > 0 ){
      testCase.expected.properties = doc.selected[ 0 ].display_name;
    }

    if( doc.foundInPelias ){
      for( var ind = doc.results.length - 1; ind >= 0; ind-- ){
        if( doc.results[ ind ].icon === 'check' ){
          testCase.expected.priorityThresh = ind + 1;
          break;
        }
      }
    }

    oldTests.push(testCase);
  });
}

function updateTestFile( path, newDocs ){
  var existingTests = JSON.parse( fs.readFileSync( path ) );
  addTests( existingTests.tests, newDocs );
  fs.writeFileSync( path, JSON.stringify( existingTests, undefined, 2 ) );
}

function updateTestFiles(){
  db.get( 'pelias' ).find( {}, function ( err, docs ){
    if( err ){
      console.error( err );
      process.exit( 1 );
    }

    if( docs.length === 0 ){
      console.error( 'No test cases found in the MongoDB Pelias collection.' );
      process.exit( 2 );
    }

    var passingDocs = [];
    var failingDocs = [];
    docs.forEach( function ( doc ){
      ( ( doc.foundInPelias ) ? passingDocs : failingDocs ).push( doc )
    });

    var testDir = './acceptance-tests/test_cases/';
    updateTestFile( testDir + 'feedback_pass.json', passingDocs );
    updateTestFile( testDir + 'feedback_fail.json', failingDocs );
    db.close();
  });
}

updateTestFiles();

@@ -309,61 +309,249 @@
 );%0A%0A
-function backupCollection( cb )%7B%0A  db.get( 'pelias' )
+/**%0A * Move all documents in the %60pelias%60 collection to a %22backup%22 %60pelias-backup%60%0A * collection and wipe %60pelias%60. Call %60cb%60 when finished.%0A */%0Afunction backupCollection( cb )%7B%0A  var peliasCollection = db.get( 'pelias' );%0A  peliasCollection
 .fin
@@ -686,28 +686,8 @@
 ()%7B%0A
-        db.close();%0A
     
@@ -715,32 +715,293 @@
    %7D);%0A  %7D);%0A%7D%0A%0A
+/**%0A * Given %60oldTests%60, which should be the %60tests%60 array property of an%0A * acceptance-tests suite, and %60newDocs%60, which is an array of documents%0A * extracted from Mongo, create new test-cases from the %60newDocs%60 records and%0A * inject them into %60oldTests%60.%0A */%0A
 function addTest
@@ -2184,24 +2184,139 @@
 );%0A  %7D);%0A%7D%0A%0A
+/**%0A * Create test-cases for all documents in %60newDocs%60 and inject them into the%0A * test-suite file at %60path%60.%0A */%0A
 function upd
@@ -2528,16 +2528,383 @@
 ) );%0A%7D%0A%0A
+/**%0A * Assuming that the %60pelias/acceptance-tests%60 repo is cloned to an%0A * %60acceptance-tests%60 directory sitting inside this directory, extract the%0A * records stored by the feedback app from MongoDB, create passing/failing test%0A * cases for them, and inject them into the %60feedback_pass.json%60 and%0A * %60feedback_fail.json%60 files in %60./acceptance-tests/test_cases/%60.%0A */%0A
 function
@@ -3545,24 +3545,63 @@
 lingDocs );%0A
+    backupCollection( function (  )%7B%0A  
     db.close
@@ -3604,16 +3604,24 @@
 lose();%0A
+    %7D);%0A
   %7D);%0A%7D%0A

Add documentation comments to generate_tests.js.