// @flow
/*
 * Uses Fuse.js to provide a fast & async search provider as a SharedWorker
 */

import Fuse from 'fuse.js';

declare var self: DedicatedWorkerGlobalScope;

let fuse;
let searchData;

const updateFuseInstance = ({ data, options }) => {
	searchData = data;
	fuse = new Fuse(searchData, options);
};

const search = str => {
	if(fuse && searchData)
		return fuse.search(str);
	else if(!searchData)
		throw new Error(`searchData is not instantiated!`);
	else if(!fuse)
		throw new Error(`fuse is not instantiated!`);
};

self.onmessage = (msg: any) => {
	const { type, payload } = msg.data;
	switch (type) {
		case 'dataChanged':
			updateFuseInstance(payload);
			break;
		case 'search':
			const result = search(payload);
			self.postMessage(result);
			break;
		default:
			console.error(`SearchWorker got undefined message: ${ type } with payload ${ payload }`);
			break;
	}
};
