"use strict";

var exec = require('child_process').exec;
var gulp = require('gulp');
var gutil = require('gulp-util');
var fs = require('fs');
var UtilElasticSearch = require('../../server/utils/UtilElasticSearch');
var path = require('path');

var logPath = "elastic-index/mongo-connector.log";

function tailConnectorLog() {

    var Tail = require('tail').Tail;
    // tail the mongo connector log file
    var tail = new Tail(logPath);

    tail.on("line", function (data) {
        gutil.log(data);
    });

    tail.on("error", function (error) {
        gutil.log('ERROR in mongo connector tail: ' + error);
    });
}

function createLogFile(){

    fs.exists(logPath, function(exists) {
        if (!exists)  {
            fs.writeFile(logPath, 'initialized log file....', function (err) {

            });
        }
    });
}

gulp.task('elastic-index',
    done => {
        var mongo = config.get('dataServices.default');
        var elastic = config.get('elasticsearch');

        var mongoHost = "localhost:27017";
        var elasticHost = "localhost:9200";
        var elasticIndexName = UtilElasticSearch.elasticIndexName;

        var oplogTimestampFile = mongo.db + ".timestamp"; // use a different timestamp file for each configured database

        var configFilePath = path.resolve(__dirname, 'mongo-connector/config.json');

        var cmd = "mongo-connector -m " + mongoHost + " -t " + elasticHost
        + " -o " + oplogTimestampFile
        + " -n " + mongo.db + ".documents -d elastic2_doc_manager --tz-aware --continue-on-error"
        + " --config-file=" + configFilePath;

        gutil.log("Mongo Connector cmd: " + cmd);

        var options = {cwd: "./elastic-index"};

        createLogFile();

        exec(cmd, options, function (err, stdout, stderr) {
            gutil.log(stdout);
            gutil.log(stderr);
            gutil.log("Mongo Connector terminated");
            done();
        });

        // tail the log after a period long enough to know that it will have been created
        var delay = 2000;

        setTimeout(tailConnectorLog, delay);
    });