'use strict'

const chokidar = require('chokidar')
const mm = require('minimatch')
const expandBraces = require('expand-braces')
const PatternUtils = require('./utils/pattern-utils')

const helper = require('./helper')
const log = require('./logger').create('watcher')

const DIR_SEP = require('path').sep

function watchPatterns (patterns, watcher) {
  let pathsToWatch = new Set()

  // expand ['a/{b,c}'] to ['a/b', 'a/c']
  expandBraces(patterns)
    .forEach((pattern) => pathsToWatch.add(PatternUtils.getBaseDir(pattern)))

  pathsToWatch = Array.from(pathsToWatch)
  // watch only common parents, no sub paths
  pathsToWatch.forEach((path) => {
    if (!pathsToWatch.some((p) => p !== path && path.startsWith(p + DIR_SEP))) {
      watcher.add(path)
      log.debug(`Watching "${path}"`)
    }
  })
}

function checkAnyPathMatch (patterns, path) {
  return patterns.some((pattern) => mm(path, pattern, {dot: true}))
}

function createIgnore (patterns, excludes) {
  return function (path, stat) {
    if (stat && !stat.isDirectory()) {
      return !checkAnyPathMatch(patterns, path) || checkAnyPathMatch(excludes, path)
    } else {
      return false
    }
  }
}

function getWatchedPatterns (patterns) {
  return patterns
    .filter((pattern) => pattern.watched)
    .map((pattern) => pattern.pattern)
}

exports.watch = function (patterns, excludes, fileList, usePolling, emitter) {
  const watchedPatterns = getWatchedPatterns(patterns)

  const watcher = new chokidar.FSWatcher({
    usePolling: usePolling,
    ignorePermissionErrors: true,
    ignoreInitial: true,
    ignored: createIgnore(watchedPatterns, excludes)
  })

  watchPatterns(watchedPatterns, watcher)

  watcher
    .on('add', (path) => fileList.addFile(helper.normalizeWinPath(path)))
    .on('change', (path) => fileList.changeFile(helper.normalizeWinPath(path)))
    .on('unlink', (path) => fileList.removeFile(helper.normalizeWinPath(path)))
    .on('error', log.debug.bind(log))

  emitter.on('exit', (done) => {
    watcher.close()
    done()
  })

  return watcher
}

exports.watch.$inject = [
  'config.files',
  'config.exclude',
  'fileList',
  'config.usePolling',
  'emitter'
]

@@ -351,39 +351,30 @@
 %7B%0A  
-let pathsToWatch = new Set()%0A%0A 
+expandBraces(patterns)
  // 
@@ -416,232 +416,172 @@
 %5D%0A  
-expandBraces(patterns)%0A    .forEach((pattern) =%3E pathsToWatch.add(PatternUtils.getBaseDir(pattern)))%0A%0A  pathsToWatch = Array.from(pathsToWatch)%0A  // watch only common parents, no sub paths%0A  pathsToWatch.forEach((path
+  .map(PatternUtils.getBaseDir)%0A    .filter((path, index, paths) =%3E paths.indexOf(path) === index) // filter unique values%0A    .forEach((path, index, paths
 ) =%3E %7B%0A
+  
     
@@ -594,15 +594,8 @@
 aths
-ToWatch
 .som
@@ -606,22 +606,8 @@
 ) =%3E
- p !== path &&
  pat
@@ -638,24 +638,26 @@
 ))) %7B%0A      
+  
 watcher.add(
@@ -658,24 +658,26 @@
 r.add(path)%0A
+  
       log.de
@@ -706,18 +706,22 @@
 %22%60)%0A    
-%7D%0A
+  %7D%0A  
   %7D)%0A%7D%0A%0A

refactor watchPatterns method