import IDUtil from '../util/IDUtil';
import SearchResults from '../model/SearchResults';
import LocalStorageHandler from '../util/LocalStorageHandler';
import FlexRouter from '../util/FlexRouter';

const SearchAPI = {

	//TODO combined search instead of a single query to multiple indices for each layer
	//TODO field specific search in search term syntax
	//TODO query should become a list of queries for each selected index
	//TODO turn the returned result into a proper SearchResult object
	search(query, collectionConfig, callback, store = true) {
		if(query.offset + query.size <= 10000) {
			let url = _config.SEARCH_API_BASE + '/layered_search/' + query.collectionId;
			const xhr = new XMLHttpRequest();
			const searchId = query.searchId || IDUtil.guid();
			xhr.onreadystatechange = function() {
				if (xhr.readyState === XMLHttpRequest.DONE) {
					if(xhr.status === 200) {
						const data = JSON.parse(xhr.responseText);
						if(data && data.params) {
							const searchResults = SearchResults.construct(searchId, false, data, collectionConfig)
							if(store) {
								LocalStorageHandler.storeJSONInLocalStorage(
									'stored-search-results',
									searchResults.toLocalStorageObject()
								);
								FlexRouter.setBrowserHistory({queryId : 'cache'}, 'single-search-history');
							}
							callback(searchResults);
						} else {
							callback({searchId : searchId, error : 'Server returned no results', query : query});
						}
					} else {
						callback({searchId : searchId, error : 'Server returned an error response', query : query});
					}
				}
			}
			xhr.open("POST", url);
			xhr.timeout = 50000;
			xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
			xhr.send(JSON.stringify(query));
		} else {
			console.debug('Currently the search engine cannot look beyond this point, please narrow your search terms');
			callback(SearchResults.construct(null, true, {params : query}, collectionConfig))
		}
	}
};

export default SearchAPI;
