/*globals describe it beforeEach afterEach */
"use strict";

require("should");
const path = require("path");
const TestHelper = require("./helpers/TestHelper");
const Watchpack = require("../lib/watchpack");
const watchEventSource = require("../lib/watchEventSource");

const fixtures = path.join(__dirname, "fixtures");
const testHelper = new TestHelper(fixtures);

describe("ManyWatchers", function() {
	this.timeout(240000);
	beforeEach(testHelper.before);
	afterEach(testHelper.after);

	it("should watch more than 4096 directories", done => {
		const files = [];
		for (let i = 1; i < 5000; i++) {
			let highBit = 1;
			let j = i;
			while (j > 1) {
				highBit <<= 1;
				j >>= 1;
			}
			const dir = `${i & highBit}/${i & ~highBit}`;
			if (i === highBit) {
				testHelper.dir(`${i}`);
				testHelper.file(`${i}/file`);
				files.push(path.join(fixtures, `${i}`, "file"));
			}
			testHelper.dir(dir);
			testHelper.file(`${dir}/file`);
			files.push(path.join(fixtures, dir, "file"));
			if (i === highBit) {
				testHelper.file(`${dir}/file2`);
				files.push(path.join(fixtures, dir, "file2"));
			}
		}
		testHelper.file("file");
		files.push(path.join(fixtures, "file"));
		testHelper.tick(10000, () => {
			const w = new Watchpack({
				aggregateTimeout: 1000
			});
			w.on("aggregated", function(changes) {
				Array.from(changes).should.be.eql([
					path.join(fixtures, "4096/900/file")
				]);
				w.close();
				done();
			});
			for (let i = 100; i < files.length; i += 987) {
				for (let j = 0; j < files.length - i; j += 987) {
					w.watch({ files: files.slice(j, j + i) });
				}
			}
			w.watch({ files });
			testHelper.tick(10000, () => {
				testHelper.file("4096/900/file");
			});
		});
	});
});

@@ -417,10 +417,10 @@
 out(
-24
+60
 0000
@@ -542,16 +542,136 @@
 ne =%3E %7B%0A
+%09%09console.time(%22creating files%22);%0A%09%09// windows is very slow in creating so many files%0A%09%09// this can take about 1 minute%0A
 %09%09const 
@@ -1299,16 +1299,53 @@
 ile%22));%0A
+%09%09console.timeEnd(%22creating files%22);%0A
 %09%09testHe
@@ -1470,24 +1470,71 @@
 (changes) %7B%0A
+%09%09%09%09console.timeEnd(%22detecting change event%22);%0A
 %09%09%09%09Array.fr
@@ -1645,16 +1645,159 @@
 %0A%09%09%09%7D);%0A
+%09%09%09console.time(%22creating/closing watchers%22);%0A%09%09%09// MacOS is very slow in creating and destroying watchers%0A%09%09%09// This can take about 2 minutes%0A
 %09%09%09for (
@@ -1828,27 +1828,28 @@
 ength; i += 
-987
+2432
 ) %7B%0A%09%09%09%09for 
@@ -1983,38 +1983,131 @@
 %0A%09%09%09
-testHelper.tick(10000, () =%3E %7B
+console.timeEnd(%22creating/closing watchers%22);%0A%09%09%09testHelper.tick(10000, () =%3E %7B%0A%09%09%09%09console.time(%22detecting change event%22);
 %0A%09%09%09

add time logging to test, make test faster, increase timeout