import MediaObject from './MediaObject';

export default class SearchResult {

	constructor(rawSearchResult, formattedData, highlights, collectionConfig) {
		//this.rawData = rawSearchResult; // a single search result from the array of results in the search API response object
		//this.formattedData = formattedData; // the result data formatted according to the collectionConfig

		Object.keys(formattedData).forEach(prop => this[prop] = formattedData[prop])

		//format the playable content into MediaObjects (TODO collectionConfig.getItemDetailData() should already do this)
		if(this.playableContent && this.playableContent.length > 0) {
			this.playableContent = this.playableContent.map(mo => MediaObject.construct(mo, collectionConfig))
		}

		this.highlights = highlights; // all fields the search term was found in WITH highlights
		this.numHighlights = Object.keys(highlights).length !== 0 ? Object.keys(highlights).reduce((acc, cur) => acc += highlights[cur].length, 0) : 0;
	}

	static construct(rawSearchResult, query, collectionConfig) { //TODO change the order so query can be made optional
		return new SearchResult(
			rawSearchResult,
			collectionConfig.getItemDetailData(
				rawSearchResult,
				query && query.dateRange ? query.dateRange.field : null
			),
			collectionConfig.getHighlights(
				rawSearchResult["_source"],
				query ? query.searchRegex : null
			),
			collectionConfig
		)
	}

}