'use strict';

const npm = require('npm');

const get = require('./get');
const lookup = require('./lookup');
const parse = require('./parse');

// TODO: Currently this is an inline config
//       Need to find out howto define config options in atom.io
let config = {
  url: 'http://some-url-to-proxy-pac',
  test_url: 'http://atom.io',
  test_host: 'atom.io'
}

/**
 * Main function to get, invoke, parse and set the proxy
 */
const atomPACProxy = () => {
  get(config.url, (err, pacdata) => {
    if(err) {
      throw err;
    }

    lookup(pacdata, config.test_url, config.test_host, (err, proxy) => {
      if(err) {
        throw err;
      }

      parse(proxy, (err, result) => {
        if(err) {
          throw err;
        }

        npm.config.set('http-proxy', result.url);
        npm.config.set('https-proxy', result.url);
      });
    });
  });
};

module.exports = atomPACProxy;

@@ -728,24 +728,262 @@
 %0A        %7D%0A%0A
+        if(!result %7C%7C result.length === 0) %7B%0A          throw new Error('No valid proxy informations found');%0A        %7D%0A%0A        let p = proxy.shift();%0A%0A        if(p.type === 'direct') %7B%0A          // pass, nothing to do%0A        %7D else %7B%0A  
         npm.
@@ -1003,37 +1003,34 @@
 ttp-proxy', 
-result
+p
 .url);%0A
+  
         npm.
@@ -1059,20 +1059,25 @@
 y', 
-result.url);
+p.url);%0A        %7D
 %0A   

handle setting of NPM proxy correct