// See COPYING for copyright and license details
(function() {
    Object.defineProperties(system, {
        "spawn" : 
        {
            value : (function() {
                return function(command, detail) {
                    detail = detail || {};
                    var onStdout = null, onStderr = null;
                    var d = new Deferred();
                    var result = { status : 0 };

                    if (detail.cacheStdout || detail.onStdout) {
                        result.stdout = "";
                        onStdout = function(response) {
                            result.stdout += response;
                            if (detail.onStdout) {
                                detail.onStdout(response);
                            }
                        };
                    }
                    if (detail.cacheStderr || detail.onStderr) {
                        result.stderr = "";
                        onStderr = function(response) {
                            result.stderr += response;
                            if (detail.onStderr) {
                                detail.onStderr(response);
                            }
                        };
                    }
                    system._spawn(command, onStdout, onStderr, detail.stdin, detail.environment).then(
                        function(status) {
                            result.status = status;
                            if (detail.onFinished) {
                                detail.onFinished(result);
                            }
                            d.resolve(result);
                        }, 
                        function(status) {
                            result.status = status;
                            if (detail.onFinished) {
                                detail.onFinished(result);
                            }
                            d.reject(result);
                        }
                    );
                    return d;
                };
            })()
        }
    });
    Object.freeze(system);
})();
