'use strict'

import {BufferedProcess} from 'atom'
const extractionRegex = /Installing (.*?) to .* (.*)/

export function installPackages(dependencies, progressCallback) {
  return new Promise(function(resolve, reject) {
    const errors = []
    new BufferedProcess({
      command: atom.packages.getApmPath(),
      args: ['install'].concat(dependencies).concat(['--production', '--color', 'false']),
      options: {},
      stdout: function(contents) {
        const matches = extractionRegex.exec(contents)
        if (matches[2] === '✓' || matches[2] === 'done') {
          progressCallback(matches[1], true)
          atom.packages.activatePackage(matches[1])
        } else {
          progressCallback(matches[1], false)
          errors.push(contents)
        }
      },
      stderr: function(contents) {
        errors.push(contents)
      },
      exit: function() {
        if (errors.length) {
          const error = new Error('Error installing dependencies')
          error.stack = errors.join('')
          reject(error)
        } else resolve()
      }
    })
  })
}

export function packagesToInstall(name) {
  let packageInfo = atom.packages.getLoadedPackage(name)

  const toInstall = [], toEnable = [];
  (packageInfo ? (packageInfo.metadata['package-deps'] ? packageInfo.metadata['package-deps'] : []) : [])
    .forEach(function(name) {
      if (!window.__steelbrain_package_deps.has(name)) {
        window.__steelbrain_package_deps.add(name)
        if (atom.packages.resolvePackagePath(name)) {
          toEnable.push(name)
        } else {
          toInstall.push(name)
        }
      }
    })

  return {toInstall, toEnable}
}

@@ -1098,22 +1098,26 @@
 unction 
-packag
+dependenci
 esToInst
@@ -1130,18 +1130,42 @@
 me) %7B%0A  
-le
+const toReturn = %5B%5D%0A  cons
 t packag
@@ -1165,20 +1165,22 @@
  package
-Info
+Module
  = atom.
@@ -1211,25 +1211,24 @@
 e(name)%0A
-%0A
   const 
 toInstal
@@ -1223,68 +1223,60 @@
 nst 
-toInstall = %5B%5D, toEnable = %5B%5D;%0A  (packageInfo ? (
+packageDependencies = packageModule && 
 package
-Info
+Module
 .met
@@ -1300,86 +1300,81 @@
 ps'%5D
- ? packageInfo.metadata%5B'package-deps'%5D : %5B%5D) : %5B%5D)
+%0A%0A  if (packageDependencies) %7B
 %0A    
-.
 for
-Each(function(name
+ (const name of packageDependencies
 ) %7B%0A
@@ -1384,23 +1384,16 @@
    if (!
-window.
 __steelb
@@ -1435,15 +1435,8 @@
     
-window.
 __st
@@ -1479,16 +1479,17 @@
     if (
+!
 atom.pac
@@ -1534,22 +1534,22 @@
       to
-Enable
+Return
 .push(na
@@ -1565,49 +1565,9 @@
    %7D
- else %7B%0A          toInstall.push(name)%0A  
+%0A
     
@@ -1574,26 +1574,21 @@
   %7D%0A    
-  
 %7D%0A  
- 
- %7D)
+%7D
 %0A%0A  retu
@@ -1594,28 +1594,15 @@
 urn 
-%7B
 to
-Install, toEnable%7D
+Return
 %0A%7D%0A

Add dependenciesToInstall helper