/**
 * process.js
 * Copyright (c) 2000 - 2017 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Contact:
 * Sungmin Kim <sm.art.kim@samsung.com>
 * Jonghwan Park <iwin100.park@samsung.com>
 * Kitae Kim <kt920.kim@samsung.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 * - S-Core Co., Ltd
**/

var spawn = require('child_process').spawn;
var readline = require('readline');
var os = require('os');


module.exports.create = createProcess;
module.exports.monitor = monitorProcess;


function createProcess(cmd, args, opts, monitor) {
    var proc = spawn(cmd, args, opts);

    // monitor process
    if (!monitor) {
        monitor = {};
    }

    if (proc) {
        monitorProcess(proc,
            monitor.onStdout,
            monitor.onStderr,
            monitor.onExit);
    }

    return proc;
}


// onStdout( line )
// onStderr( line )
// onExit( exitCode, exitErr )
function monitorProcess(proc, onStdout, onStderr, onExit) {
    var exitCode = -1;
    var exitErr = null;
    var closeCnt = 0;

    // create readline interface
    var readStdout = readline.createInterface({
        input: proc.stdout,
        terminal: false
    });
    var readStderr = readline.createInterface({
        input: proc.stderr,
        terminal: false
    });

    readStdout.on('line', function (line) {
        if (onStdout) {
            onStdout(line.toString());
        }
    });

    readStderr.on('line', function (line) {
        if (onStderr) {
            onStderr(line.toString());
        }
    });

    readStdout.on('close', function () {
        closeCnt++;
        if (closeCnt === 3 && onExit) {
            onExit(exitCode, exitErr);
        }
    });
    readStderr.on('close', function () {
        closeCnt++;
        if (closeCnt === 3 && onExit) {
            onExit(exitCode, exitErr);
        }
    });

    proc.on('error', function (err) {
        closeCnt++;
        // NOTE. On windows, readline do not invoke 'close' event if error
        if (os.platform() === 'win32') {
            closeCnt++;
        }
        exitErr = err;
    });

    proc.on('close', function (code) {
        closeCnt++;
        exitCode = code;
        if (closeCnt === 3 && onExit) {
            onExit(exitCode, exitErr);
        }
    });
}
