import validate from '../utils/validate'

const hooks = new Map()
const patternHooks = new Map()

// matches actions with letter/number characters & -, _
const actionRegex = /^[A-Za-z0-9-_]+\/[A-Za-z0-9-_]+$/
const isAction = matcher => !!matcher.match(actionRegex)

const createHook = (
  matcher: string,
  onAction: (action: $action) => void
) => {
  validate([
    [typeof matcher !== 'string', 'hook matcher must be a string'],
    [typeof onAction !== 'function', 'hook onAction must be a function'],
  ])

  if (!isAction(matcher)) {
    hooks.set(matcher, onAction)
  } else {
    // TODO: validate is valid action first
    // examples: *, */*, a/*, */b, a*/b, a/b*, etc.

    // set as a pattern hook, if hook does not match a specific action
    patternHooks.set(matcher, onAction)
  }
}

export default () => ({
  onModel: (model) => {
    Object.keys(model.hooks || {}).forEach((matcher: string) => {
      createHook(matcher, model.hooks[matcher])
    })
  },
  middleware: () => next => action => {
    const { type } = action
    // exact match
    if (hooks.has(type)) {
      hooks.get(type)(action)
    } else {
      // run matches on pattern hooks
      patternHooks.forEach((onAction: (action: $action) => void, matcher: string) => {
        if (type.match(new RegExp(matcher))) {
          onAction(action)
        }
      })
    }
    return next(action)
  }
})

@@ -62,39 +62,8 @@
 ap()
-%0Aconst patternHooks = new Map()
 %0A%0A//
@@ -481,17 +481,16 @@
 %0A%0A  if (
-!
 isAction
@@ -554,211 +554,73 @@
     
-// TODO: validate is valid action first%0A    // examples: *, */*, a/*, */b, a*/b, a/b*, etc.%0A%0A    // set as a pattern hook, if hook does not match a specific action%0A    patternHooks.set(matcher, onAction)
+matcher = matcher.replace('*', '.*')%0A    matcher = %60%5E$%7Bmatcher%7D$%60
 %0A  %7D
@@ -907,24 +907,24 @@
 as(type)) %7B%0A
+
       hooks.
@@ -945,239 +945,8 @@
 on)%0A
-    %7D else %7B%0A      // run matches on pattern hooks%0A      patternHooks.forEach((onAction: (action: $action) =%3E void, matcher: string) =%3E %7B%0A        if (type.match(new RegExp(matcher))) %7B%0A          onAction(action)%0A        %7D%0A      %7D)%0A
     

disable pattern matching hooks.