import CollectionConfig from './CollectionConfig';

class NISVCatalogueConfig extends CollectionConfig {
	constructor(clientId, user, collectionId, stats, info) {
		super(clientId, user, collectionId, stats, info);
	}

	getNamespace() {
		return 'http://av.beeldengeluid.nl/';
	}

	//the type varies for B&G
	getCollectionMediaTypes() {
		return [];
	}

	//used to prevent graphs to blow up in case the minimum date is really low (because of incorrect data)
	getMinimunYear() {
		return 1850;
	}

	//override the nisv-catalogue-aggr__layer_asr
	getCollectionIndices() {
	 	return ['nisv-catalogue-aggr']
	}

	getVideoBaseUrl() {
		return 'http://lbas2.beeldengeluid.nl:8093/viz';
	}

	getAudioBaseUrl() {
		return 'http://ltas1.beeldengeluid.nl:8093/viz';
		//return 'http://lbas2.beeldengeluid.nl:8093/avid';
	}

	requiresPlayoutAccess() {
		return false;
	}

	getPreferredDateField() {
		return 'bg:publications.bg:publication.bg:sortdate';
	}

	getFacets() {
		return [
			{
				field: 'bg:publications.bg:publication.bg:broadcasters.bg:broadcaster',
				title : 'Broadcaster',
				id : 'broadcaster',
				type : 'string'
			},
			{
				field: 'bga:series.bg:genres.bg:genre.keyword',
				title : 'Genre (series)',
				id : 'genre',
				type : 'string'
			},
			{
				field: 'bg:keywords.bg:keyword.keyword',
				title : 'Keyword',
				id : 'keyword',
				type : 'string'
			}
		];
	}

	getMetadataFieldCategories() {
		return [
			{
				id : 'titles',
				label : 'Titles',
				fields : [
					'bga:series.bg:maintitles.bg:title',
					'bga:season.bg:maintitles.bg:title',
					'bga:segment.bg:maintitles.bg:title',
					'bg:maintitles.bg:title'
				]
			},
			{
				id : 'descriptions',
				label : 'Descriptions',
				fields : [
					'bg:summary',
					'bg:description',
					'bga:segment.bg:description',
					'bg:museum-description',
					'bga:series.bg:museum-description',
					'bga:segment.bg:museum-description'
				]
			},
			{
				id : 'subtitles',
				label : 'Subtitles',
				fields : [
					'bg:transcripts.bg:transcript.bg:text',
					'bga:segment.bg:transcripts.bg:transcript.bg:text'
				]
			},
			{
				id : 'asr',
				label : 'Spraaktranscripten',
				nestedPath : 'layer__asr',
				fields : [
					'layer__asr.words'
				]
			}
		]
	}

	getItemDetailData(result, currentDateField) {
		result = this.formatSearchResult(result);
		const formattedResult = {}
		formattedResult.resourceId = result._id;
		formattedResult.index = result._index;
		formattedResult.docType = result._type;
		formattedResult.title = this.__extractTitle(result);
		formattedResult.description = this.__extractDescription(result);
		const dateInfo = this.__extractDateInfo(result, currentDateField);
		if(dateInfo) {
			formattedResult.date = dateInfo.date;
			formattedResult.dateField = dateInfo.field;
		}
		formattedResult.externalSourceInfo = this.__getExternalSourceInfo(result);
		formattedResult.specialProperties = this.__extractSpecialProperties(result);

		const content = this.__extractPlayableContent(result);
		formattedResult.playableContent = content.playableContent;
		formattedResult.mediaTypes = content.mediaTypes;
		formattedResult.rawData = result;

		/*
		//THIS IS ONLY WHEN USING THE MULTI-LAYERED APPROACH OF HAVING MULTIPLE INDEXES
		//if the user did not specify a search string there will be no inner hits and thus no fragment metadata!

		//the media fragment is passed to the resource viewer, so it will skip to that piece of media
		//TODO this should be changed, since the media fragment is now reflected as a URL, which should be hidden to
		//prevent easily downloading it
		if(result._type == 'media_fragment' &&
			formattedResult.playableContent &&
			formattedResult.playableContent.length > 0) {
			formattedResult.mediaFragment = {
				url : formattedResult.playableContent[0].url,
				assetId : formattedResult.playableContent[0].assetId,
				start : result.start || 0,
				end : result.start + result.duration || 5000,
				snippet : result.words ? '(...) "' + result.words  + '" (...)' : '',
				layer : 'asr'
			}

		}*/

		return formattedResult;
	}

	toPrettyFieldName(esFieldName) {
		if(esFieldName) {
			//first split the field based on a dot
			let tmp = esFieldName.split('.');

			// remove namespaces
			tmp = tmp.map((field)=>(field.substring(field.indexOf(":") + 1)));

			let isKeywordField = false;

			//if the last field is called raw or keyword (ES reserved names), drop it
			if(tmp[tmp.length -1] == 'raw' || tmp[tmp.length -1] == 'keyword') {
				isKeywordField = true;
				tmp.pop();
			}

			let leaf = tmp.pop();

			// move @ to end of fieldname
			if (leaf.substring(0,1) == '@'){
				leaf = leaf.substring(1) + '@';
			}
			let origin = tmp.join(".");
			if (origin){
				origin = ' => ' + origin;
			}
			return leaf + origin + (isKeywordField ? ' *' : '');
		}
		return esFieldName;
	}

	__extractTitle(result) {
		let title = null;
		//first check the series title
		if (result.hasOwnProperty('bga:series')) {
			const series = result['bga:series'];
			if (series.hasOwnProperty('bg:maintitles') && series['bg:maintitles'].hasOwnProperty('bg:title')) {
				title = series['bg:maintitles']['bg:title'].join(' / ');
			}
		}
		//then check the season title
		if (result.hasOwnProperty('bga:season')) {
			const season = result['bga:season'];
			if (season.hasOwnProperty('bg:maintitles') && season['bg:maintitles'].hasOwnProperty('bg:title')) {
				title = title ? title + '; ' : '';
				title += season['bg:maintitles']['bg:title'].join(' / ');
			}
		}
		//then check the expression title
		if (result.hasOwnProperty('bg:maintitles') && result['bg:maintitles'].hasOwnProperty('bg:title')) {
			title = title ? title + ': ' : '';
			title += result['bg:maintitles']['bg:title'].join(' / ');
			if (result.hasOwnProperty('bg:subtitles') && result['bg:subtitles'].hasOwnProperty('bg:title')) {
				title += ' - ' + result['bg:subtitles']['bg:title'].join('; ');
			}
		}
		return title;
	}

	__extractDescription(result) {
		if (result.hasOwnProperty('bg:summary')) {
			return result['bg:summary'];
		} else {
			const temp = [result.broadcaster, result.genre]
			return temp.filter((d) => {return d ? true : false}).join(' ');
		}
		return null;
	}

	__extractDateInfo(result, currentDateField) {
		let usePublicationDate = true;
		if(currentDateField) {
			//console.debug(currentDateField);
			//if the selected date field is something else than the default sortdate try to fetch something different
			if(currentDateField.indexOf('sortdate') == -1) {

			}

		}
		if(usePublicationDate) {
			if (result.hasOwnProperty('bg:publications') && result['bg:publications'].hasOwnProperty('bg:publication')) {
				let pubs = result['bg:publications']['bg:publication'];
				if(pubs.hasOwnProperty('bg:sortdate')) {
					return {
						date : pubs['bg:sortdate'],
						field : 'bg:publications.bg:publication.bg:sortdate'
					}
				} else if(pubs.map) { //make sure it is actually an array
					return {
						date : pubs.map((pub) => {
							return pub.hasOwnProperty('bg:sortdate') ? pub['bg:sortdate'] : '';
						}).join(' / '),
						field : 'bg:publications.bg:publication.bg:sortdate'
					}
				}
			}
		}
		return null;
	}

	__extractPlayableContent(result) {
		let playableContent = null;
		let mediaTypes = null;

		let guci = null;
		let dmguid = null;
		let mimeType = 'video/mp4';

		//determine whether the content is radio or not
		if(result.hasOwnProperty('bga:series')) {
			const series = result['bga:series'];
			if(series.hasOwnProperty('bg:distributionchannel') &&
				result['bga:series']['bg:distributionchannel'].toLowerCase() == 'radio') {
				mimeType = 'audio/mp3';
			} else if (series.hasOwnProperty('bg:catalog') && series['bg:catalog'] == 'Foto') {
				mimeType = 'image/jpeg';
			}
		}

		if(result['bg:carriers'] && result['bg:carriers']['bg:carrier']) {
			let carriers = result['bg:carriers']['bg:carrier'];
			carriers = carriers.hasOwnProperty('bg:carrierreference') ? [carriers] : carriers;
			playableContent = carriers.filter(c => c['bg:carriertype'] == 'media archive')
			.sort((a,b) => parseInt(a['bg:sequencenumber'] > b['bg:sequencenumber']))
			.map(c => {
				return {
					url : mimeType == 'audio/mp3' ?
						this.getAudioBaseUrl() + '/' + c['bg:carrierreference'] :
						this.getVideoBaseUrl() + '/' + c['bg:carrierreference'],
					mimeType : mimeType,
					assetId : c['bg:carrierreference']
				}
			})
		}

		//set the media types for the search snippet media type icon
		mediaTypes = ['image'];
		mediaTypes = mimeType == 'audio/mp3' ? ['audio'] : ['video'];


		/*

		//look through the carriers	to fetch the dmguid / guci needed to build the play-out URL
		if(result.hasOwnProperty('bg:carriers')) {
			const temp = result['bg:carriers'];
			if(temp.hasOwnProperty('bg:carrier')) {
				let carriers = temp['bg:carrier'];
				if(carriers.hasOwnProperty('bg:carriertype')) {
					carriers = [carriers];
				}
				carriers = carriers.filter((c) => {
					if(c.hasOwnProperty('bg:carriertype')) {
						return c['bg:carriertype'] == 'media archive';
					}
				});

				guci = carriers.length > 0 ? carriers[0]['bg:carrierreference'] : null;
				dmguid = carriers.length > 0 ? carriers[0]['bg:dmguid'] : null;
			}
		}

		//finall assign the results to the playableContent (also fill in the found media types)
		if(mimeType == 'audio/mp3' && dmguid) {
			//let audioUrl = this.getAudioBaseUrl() + '/nisv-catalogue-aggr/';
			//audioUrl += dmguid + '?cid=' + _clientId + '&at=' + _chickenStock;
			playableContent = [{
				url : this.getAudioBaseUrl() + '/' + guci,
				mimeType : mimeType,
				assetId : this.getNamespace() + guci
			}];
			mediaTypes = ['audio'];
		} else if(mimeType == 'video/mp4' && guci) {
			let videoUrl = this.getVideoBaseUrl() + '/nisv-catalogue-aggr/';
			videoUrl += guci + '?cid=' + _clientId + '&at=' + _chickenStock;
			playableContent = [{
				url : this.getVideoBaseUrl() + '/' + guci,
				mimeType : mimeType,
				assetId : this.getNamespace() + guci
			}];
			mediaTypes = ['video'];
		} else if(mimeType == 'image/jpeg') {
			mediaTypes = ['image'];
		}

		*/

		return {
			playableContent : playableContent,
			mediaTypes : mediaTypes
		}
	}

	__getExternalSourceInfo(result) {
		if(result.hasOwnProperty('dc:relation')) {
			return {
				url :result['dc:relation'],
				message : null
			}
		}
		return null;
	}

	//these are the properties that will be shown in the regular item details table
	__extractSpecialProperties(result) {
		const specialProperties = {};
		//broadcaster
		if (result.hasOwnProperty('bg:publications') && result['bg:publications'].hasOwnProperty('bg:publication')) {
			if (result['bg:publications']['bg:publication'].hasOwnProperty('bg:broadcasters')) {
				specialProperties['Broadcaster'] = result['bg:publications']['bg:publication']['bg:broadcasters']['bg:broadcaster'];
			}
		}
		//genre
		if (result.hasOwnProperty('bg:genres') && result['bg:genres'].hasOwnProperty('bg:genre')) {
			specialProperties['Genre'] = result['bg:genres']['bg:genre'];
		}
		return specialProperties;
	}

}

export default NISVCatalogueConfig;