'use strict'

const fs = require('graceful-fs')
const path = require('path')
const helper = require('./helper')

const log = require('./logger').create('plugin')

const IGNORED_PACKAGES = ['karma-cli', 'karma-runner.github.com']

function resolve (plugins, emitter) {
  const modules = []

  function requirePlugin (name) {
    log.debug(`Loading plugin ${name}.`)
    try {
      modules.push(require(name))
    } catch (e) {
      if (e.code === 'MODULE_NOT_FOUND' && e.message.includes(name)) {
        log.error(`Cannot find plugin "${name}".\n  Did you forget to install it?\n  npm install ${name} --save-dev`)
      } else {
        log.error(`Error during loading "${name}" plugin:\n  ${e.message}`)
      }
      emitter.emit('load_error', 'plug_in', name)
    }
  }

  plugins.forEach(function (plugin) {
    if (helper.isString(plugin)) {
      if (!plugin.includes('*')) {
        requirePlugin(plugin)
        return
      }
      const pluginDirectory = path.normalize(path.join(__dirname, '/../..'))
      const regexp = new RegExp(`^${plugin.replace('*', '.*')}`)

      log.debug(`Loading ${plugin} from ${pluginDirectory}`)
      fs.readdirSync(pluginDirectory)
        .filter((pluginName) => !IGNORED_PACKAGES.includes(pluginName) && regexp.test(pluginName))
        .forEach((pluginName) => requirePlugin(`${pluginDirectory}/${pluginName}`))
    } else if (helper.isObject(plugin)) {
      log.debug(`Loading inline plugin defining ${Object.keys(plugin).join(', ')}.`)
      modules.push(plugin)
    } else {
      log.error(`Invalid plugin ${plugin}`)
      emitter.emit('load_error', 'plug_in', plugin)
    }
  })

  return modules
}

/**
  Create a function to handle errors in plugin loading.
  @param {Object} injector, the dict of dependency injection objects.
  @return function closed over injector, which reports errors.
*/
function createInstantiatePlugin (injector) {
  const emitter = injector.get('emitter')
  // Cache to avoid report errors multiple times per plugin.
  const pluginInstances = new Map()
  return function instantiatePlugin (kind, name) {
    if (pluginInstances.has(name)) {
      return pluginInstances.get(name)
    }

    let p
    try {
      p = injector.get(`${kind}:${name}`)
      if (!p) {
        log.error(`Failed to instantiate ${kind} ${name}`)
        emitter.emit('load_error', kind, name)
      }
    } catch (e) {
      if (e.message.includes(`No provider for "${kind}:${name}"`)) {
        log.error(`Cannot load "${name}", it is not registered!\n  Perhaps you are missing some plugin?`)
      } else {
        log.error(`Cannot load "${name}"!\n  ` + e.stack)
      }
      emitter.emit('load_error', kind, name)
    }
    pluginInstances.set(name, p, `${kind}:${name}`)
    return p
  }
}

createInstantiatePlugin.$inject = ['injector']

module.exports = { resolve, createInstantiatePlugin }

@@ -1062,16 +1062,44 @@
 ace(
-'*', '.*
+/%5C*/g, '.*').replace(/%5C//g, '%5B/%5C%5C%5C%5C%5D
 ')%7D%60
@@ -1213,22 +1213,383 @@
    .
-filter((plugin
+map((e) =%3E %7B%0A          const modulePath = path.join(pluginDirectory, e)%0A          if (e%5B0%5D === '@') %7B%0A            return fs.readdirSync(modulePath).map((e) =%3E path.join(modulePath, e))%0A          %7D%0A          return modulePath%0A        %7D)%0A        .reduce((a, x) =%3E a.concat(x), %5B%5D)%0A        .map((modulePath) =%3E path.relative(pluginDirectory, modulePath))%0A        .filter((module
 Name
@@ -1620,22 +1620,22 @@
 ncludes(
-plugin
+module
 Name) &&
@@ -1647,22 +1647,22 @@
 xp.test(
-plugin
+module
 Name))%0A 
@@ -1707,19 +1707,26 @@
 ePlugin(
-%60$%7B
+path.join(
 pluginDi
@@ -1736,12 +1736,10 @@
 tory
-%7D/$%7B
+, 
 plug
@@ -1744,18 +1744,17 @@
 uginName
-%7D%60
+)
 ))%0A    %7D

add support wildcard config for scoped package plugin (#3659)