const Randoma = require('randoma');
const fs = require('fs');
const path = require('path');

class Context {

	constructor (dir, seed) {
		this.dir = dir;
		this.seed = seed;
	}

	async loadFiles (filter) {
		return this.files = await this.getFiles(filter);
	}

	async getFiles (filter) {
		let files = await readdir(this.dir);
		let f = [];

		files.forEach((file) => {
			if(filter && !filter(file)) return;

			f.push(file);
		});

		files = f;

		files = shuffle(files, this.seed);

		return files;
	}

	indexOf (file) {
		return this.files.indexOf(file);
	}

	getFile (index) {
		return this.files[index];
	}

	file (x) {
		return path.join(this.dir, x);
	}

}

function shuffle(array, seed) {
  const random = new Randoma({ seed: seed });
  let currentIndex = array.length, temporaryValue, randomIndex;

  while (0 !== currentIndex) {
    randomIndex = Math.floor(random.floatInRange(0, 1) * currentIndex);
    currentIndex -= 1;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

function readdir (dir) {
	return new Promise ((done, error) => {
		fs.readdir(dir, (err, data) => {
			if(err) return error(err);
			else done(data);
		});
	});
}

module.exports = Context;