'use babel'

/* @flow */

import Path from 'path'
import {exists} from './common'
import type {Ucompiler$Plugins, UCompiler$Plugin, Ucompiler$Config$Rule} from '../types'

export async function getPlugins(rootDirectory: string, config: Ucompiler$Config$Rule): Promise<Ucompiler$Plugins> {
  const plugins = {
    compilers: [],
    preprocessors: [],
    general: [],
    minifiers: []
  }

  for (const pluginName of config.plugins) {
    const plugin = await getPlugin(rootDirectory, pluginName)

    if (typeof plugin !== 'object') {
      throw new Error(`Plugin '${pluginName}' is invalid`)
    }
    plugin.name = pluginName

    if (plugin.compiler) {
      plugins.compilers.push(plugin)
    } else if (plugin.minifier) {
      plugins.minifiers.push(plugin)
    } else if (plugin.preprocessor) {
      plugins.preprocessors.push(plugin)
    } else {
      plugins.general.push(plugin)
    }
  }

  return plugins
}

export async function getPlugin(rootDirectory: string, pluginName: string): UCompiler$Plugin {
  if (pluginName.indexOf('ucompiler-plugin-') !== 0) {
    pluginName = 'ucompiler-plugin-' + pluginName
  }
  const pluginDirectory = Path.join(rootDirectory, 'node_modules', pluginName)
  if (await exists(pluginDirectory)) {

    try {
      // $FlowIgnore: Flow does not allow non-literal require paths
      return require(pluginDirectory)
    } catch (_) {
      try {
        // $FlowIgnore: Flow does not allow non-literal require paths
        return require(pluginName)
      } catch (__) {
        throw _
      }
    }
  } else throw new Error(`'${pluginName}' not found in ${rootDirectory}`)
}

@@ -1244,21 +1244,8 @@
 ) %7B%0A
-%0A    try %7B%0A  
     
@@ -1262,58 +1262,9 @@
 nore
-: Flow does not allow non-literal require paths%0A  
+%0A
     
@@ -1301,36 +1301,18 @@
 )%0A  
-  %7D catch (_) %7B%0A    
+%7D%0A
   try %7B%0A
     
@@ -1307,20 +1307,16 @@
   try %7B%0A
-    
     // $
@@ -1329,60 +1329,9 @@
 nore
-: Flow does not allow non-literal require paths%0A    
+%0A
     
@@ -1355,18 +1355,19 @@
 ugin
-Name)%0A    
+Directory)%0A
   %7D 
@@ -1378,17 +1378,16 @@
 h (_
-_
 ) %7B%0A    
     
@@ -1386,43 +1386,8 @@
     
-    throw _%0A      %7D%0A    %7D%0A  %7D else 
 thro
@@ -1447,10 +1447,14 @@
 tory%7D%60)%0A
+  %7D%0A
 %7D%0A

Make requires work globally