const { promisify } = require('util');
const fs = require('fs');
const glob = promisify(require('glob'));
const excludeList = require('../json/exclude-from-list.json');
const excludeAutoSuggest = require('../json/exclude-from-autosuggest.json');
const autoSuggestList = { items: [] };
const componentList = {items: []};
const list = {};

Promise.all([
	glob('**/*.html', {cwd: 'src/prototype-randstad'})
])
	.then(([paths])=>{

		let stringifiedPaths = paths.toString();
		let pathArray = stringifiedPaths.split(',');

		pathArray.map(item => {
			const name = item.split('/').pop();
			const category = item.substr(0, item.lastIndexOf('.')).replace(/\//g, ' > ');
			const prettyCategory = category.substring(3);
			autoSuggestList.items.push(name.substr(0, name.lastIndexOf('.')));
			componentList.items.push({ link: item, text: name.substr(0, name.lastIndexOf('.')), category: prettyCategory});
		});

		componentList.items.sort(function (a,b) {
			let nameA=a.text.toLowerCase();
			let nameB=b.text.toLowerCase();
			if (nameA < nameB)
				return -1;
			if (nameA > nameB)
				return 1;
			return 0
		});

		const finalListItems = componentList.items.filter(({ link: id1 }) => !excludeList.items.some(({ link: id2 }) => id2 === id1));
		const finalAutoSuggestList = autoSuggestList.items.filter(function(obj) { return excludeAutoSuggest.items.indexOf(obj) === -1; });

		const names = JSON.stringify(finalAutoSuggestList.toString());
		list.items = finalListItems;
		const finalList = JSON.stringify(list);


		fs.writeFile('src/prototype-randstad/_assets/json/autosuggest-list.json', names, 'utf8', () => {});
		fs.writeFile('src/prototype-randstad/_assets/json/component-list.json', finalList, 'utf8', () => {});
	});
