"use strict";
var child_process = require("child_process");
var fs = require("fs");
var http = require("http");
var path = require("path");
var q = require("q");
var config_1 = require("./config");
function spawnFactory(sync) {
    return function (cmd, args, stdio, opts) {
        if ((config_1.Config.osType() === 'Windows_NT') && (cmd.slice(-4) !== '.exe')) {
            if (fs.existsSync(cmd + '.exe')) {
                cmd += '.exe';
            }
            else {
                args = ['/c'].concat([cmd], args);
                cmd = 'cmd';
            }
        }
        if (stdio) {
            opts = opts || {};
            opts.stdio = stdio;
        }
        if (sync) {
            return child_process.spawnSync(cmd, args, opts);
        }
        else {
            return child_process.spawn(cmd, args, opts);
        }
    };
}
exports.spawn = spawnFactory(false);
exports.spawnSync = spawnFactory(true);
function request(method, port, path, timeout, data) {
    var headers = {};
    var hasContent = data && ((method == 'POST') || (method == 'PUT'));
    if (hasContent) {
        data = data ? JSON.stringify(data) : '';
        headers['Content-Length'] = data.length;
        headers['Content-Type'] = 'application/json;charset=UTF-8';
    }
    return q.Promise(function (resolve, reject) {
        var unexpectedEnd = function () {
            reject({ code: 'UNKNOWN', message: 'Request ended unexpectedly' });
        };
        var req = http.request({ port: parseInt(port), method: method, path: path, headers: headers }, function (res) {
            req.removeListener('end', unexpectedEnd);
            if (res.statusCode !== 200) {
                reject({ code: res.statusCode, message: res.statusMessage });
            }
            else {
                var buffer_1 = [];
                res.on('data', buffer_1.push.bind(buffer_1));
                res.on('end', function () {
                    resolve(buffer_1.join('').replace(/\0/g, ''));
                });
            }
        });
        if (timeout) {
            req.setTimeout(timeout, function () {
                reject({ code: 'TIMEOUT', message: 'Request timed out' });
            });
        }
        req.on('error', reject);
        req.on('end', unexpectedEnd);
        if (hasContent) {
            req.write(data);
        }
        req.end();
    });
}
exports.request = request;
function adb(sdkPath, port, command, timeout, args) {
    return q.Promise(function (resolve, reject) {
        var child = exports.spawn(path.resolve(sdkPath, 'platform-tools', 'adb'), ['-s', 'emulator-' + port, command].concat(args || []), 'pipe');
        var done = false;
        var buffer = [];
        child.stdout.on('data', buffer.push.bind(buffer));
        child.on('error', function (err) {
            if (!done) {
                done = true;
                reject(err);
            }
        });
        child.on('exit', function (code, signal) {
            if (!done) {
                done = true;
                if (code === 0) {
                    resolve(buffer.join(''));
                }
                else {
                    reject({
                        code: code,
                        message: 'abd command "' + command + '" ' +
                            (signal ? 'received signal ' + signal : 'returned with a non-zero exit code') +
                            'for emulator-' + port
                    });
                }
            }
        });
        if (timeout) {
            setTimeout(function () {
                if (!done) {
                    done = true;
                    child.kill();
                    reject({
                        code: 'TIMEOUT',
                        message: 'adb command "' + command + '" timed out for emulator-' + port
                    });
                }
            }, timeout);
        }
    });
}
exports.adb = adb;
//# sourceMappingURL=utils.js.map