'use strict';

var chokidar = require('chokidar');
var signal = require('./signal');

var Watcher = function () {
    var output = signal();
    var watcher;
    var pending = [];
    var debounceId;

    var debouncedEmit = function () {
        if (debounceId !== undefined) {
            clearTimeout(debounceId);
        }
        debounceId = setTimeout(emit, 60);
    };

    var emit = function () {
        output.push(pending);
        pending = [];
    };

    this.listen = output.map.bind(output);

    this.watch = function (paths) {
        if (watcher !== undefined) {
            watcher.close();
        }

        watcher = chokidar.watch(paths, { persistent: false, useFsEvents: false });
        watcher.on('change', function (path) {
            if (pending.indexOf(path) === -1) {
                pending.push(path);
                debouncedEmit();
            }
        });
    };
};

Watcher.create = function () {
    return new Watcher();
};

module.exports = Watcher.create;

@@ -138,25 +138,8 @@
 ();%0A
-    var watcher;%0A
     
@@ -175,16 +175,286 @@
 ounceId;
+%0A    var watcher = chokidar.watch(%5B%5D, %7B persistent: false, useFsEvents: false %7D);%0A    var watched = %5B%5D;%0A%0A    watcher.on('change', function (path) %7B%0A        if (pending.indexOf(path) === -1) %7B%0A            pending.push(path);%0A            debouncedEmit();%0A        %7D%0A    %7D);
 %0A%0A    va
@@ -797,24 +797,91 @@
 ) %7B%0A        
+watcher.add(paths);%0A    %7D;%0A%0A    this.close = function () %7B%0A        
 if (watcher 
@@ -939,283 +939,8 @@
    %7D
-%0A%0A        watcher = chokidar.watch(paths, %7B persistent: false, useFsEvents: false %7D);%0A        watcher.on('change', function (path) %7B%0A            if (pending.indexOf(path) === -1) %7B%0A                pending.push(path);%0A                debouncedEmit();%0A            %7D%0A        %7D);
 %0A   

add close() to watcher