'use strict';

var childProcess = require('child_process');
var url = require('url');
var launcher = require('./launcher');
module.exports = function (filename, config) {
  var child = childProcess.spawn('node', ['--inspect=9331', filename, '-V'].concat(process.argv.slice(2).filter(function (arg) {
    return arg !== '--debug';
  })), {
    stdio: ['inherit', 'pipe', 'pipe']
  });
  var inspectorUrl = null;
  child.stderr.on('data', function (data) {
    var match = /(chrome-devtools:\/\/.*)\n/.exec(data.toString());
    if (match && inspectorUrl !== false) {
      var urlObj = url.parse(match[1].replace('127.0.0.1', config.ip));
      urlObj.protocol = 'http';
      urlObj.host = config.ip + ':' + config.port;
      urlObj.pathname = '/inspector/inspector.html';
      inspectorUrl = url.format(urlObj);
    }
  });

  child.stdout.on('data', function (data) {
    if (/Debug Server online/i.test(data.toString())) {
      if (inspectorUrl) {
        var _url = inspectorUrl;
        setTimeout(function () {
          launcher.launchChrome(_url);
        }, 500);

        inspectorUrl = false;
      }
    }
  });
  child.stdout.pipe(process.stdout);
  child.stderr.pipe(process.stderr);
};