'use strict';

var gulp = require('gulp');
var exec = require('child_process').exec;
var gutil = require('gulp-util');

gulp.task('restore-couchbase-db', done => {
    var bucketName = config.get("couchbase.bucket");
    var host = config.get("couchbase.host");
    var userName = config.get("couchbase.userName");
    var password = config.get("couchbase.password");
    var cmd = "cbrestore couchbaseBackup "+host+" --bucket-source="+bucketName+" --bucket-destination=fieldtec -u "+
        userName+" -p "+password;
    var options;
    gutil.log('Initializing Restore process...');
    exec(cmd, options, function (err, stdout, stderr) {
        gutil.log(stdout);
        gutil.log(stderr);
        gutil.log("Database Restored...");
        gutil.log("Initiating Re-index...");

        var N1qlQuery = require('couchbase').N1qlQuery;
        var couchbase = require('../../server/database/providers/couchbase/CouchbaseConnection');
        var fs = require('fs');

        fs.readFile('couchbase_index/CouchBaseIndexCreation.txt', function (err, data) {
            if (err) {
                throw err;
                gutil.log(err);
            }

            var st = data + "";
            var s = st.replace("\r","").split("\n");
            couchbase.initialise();

            for(var a=0; a<=s.length;a++) {
                var statement = s[a];

                var query = N1qlQuery.fromString(statement);
                var cbBucket = couchbase.getBucket();

                gutil.log(query);
                cbBucket.query(query, function(err, results) {
                    if(err) {
                        gutil.log(err);
                    } else {
                        gutil.log(results);
                    }
                });
            }

            done();
        });
    });
});