import CollectionConfig from './CollectionConfig';

export class EYEDesmetFilmConfig extends CollectionConfig {

	constructor(clientId, user, collectionId, collectionMetadata) {
		super(clientId, user, collectionId, collectionMetadata);
	}

	getCollectionMediaTypes() {
		return ['video'];
	}

	requiresPlayoutAccess() {
		return true;
	}

	// format accepted are : yyyy with some records containing strings added to it.
	getFormattedDates(date) {
		if (date && typeof(date) === 'string') {
			const newTimeStamp = new Date(date.trim()).getTime();
			if (isNaN(newTimeStamp)) {
				// assuming yyyy1; yyyy2 format. Evaluating if the first year is actually a numeric year
				return !isNaN(date.substr(0, 4)) ? [date.substr(0, 4)] : null;

			} else {
				return [date.trim()];
			}
		}
		return null;
	}

	getKeywordFields(){
		let keywordFields = [];
		for (let i = 0; i < this.keywordFields.length; i++){
			if (this.keywordFields[i].toLowerCase().indexOf("datum") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("jaar") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("synopsis") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("bron") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("affiches") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("diva") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("curator's comments") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("filmbestand") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("overige informatie") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("toelichting") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("url") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("video") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("title") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("titel") === -1 &&
				this.keywordFields[i].toLowerCase().indexOf("beschrijving") === -1){
				keywordFields.push(this.keywordFields[i])
			}
		}
		return keywordFields;
	}

	getMetadataFieldCategories() {
		return [
			{
				'id' : 'titles',
				'label' : 'Titles',
				'fields' : [
					'Gegeven titel',
					'Originele titel',
					'Mogelijke titel',
					'Basement titel',
					'Basement engelse titel',
					'Basement engelse sorteertitel',
					'Basement sorteertitel',
					'Buitenlandse release-titel',
					'Vertaalde titel',
					'Voormalige titel EYE',
					'Alternatieve titel',
					'Tussentitels',
					'Nederlandse titel',
					'Verzameltitel amateurfilm',
					'Campagnetitel reclame',
					'Producttitel reclame',
					'Aanloopstrooktitel',
					'Soort en titel',
					'Serietitel',
					'Episodetitel',
					'Werktitel',
					'Bliktitel',
					'Kopietitel'
				]
			},
			{
				'id' : 'descriptions',
				'label' : 'Descriptions',
				'fields' : [
					'Lange beschrijving',
					'Korte beschrijving',
					'Basement browse synopsis (EN)',
					'Basement browse synopsis (NL)',
					'Basement schat synopsis (EN)',
					'Basement schat synopsis (NL)',
					'Film-in-Nederland synopsis (EN)',
					'Film-in-Nederland synopsis (NL)'
				]
			}
		]
	}

	getFacets() {
		return [
			{
				field: 'Acteur.keyword',
				title : 'Acteur',
				id : 'acteur',
				type : 'string'
			},
			{
				field: 'Productiemaatschappij.keyword',
				title : 'Productiemaatschappij',
				id : 'productiemaatschappij',
				type : 'string'
			}

		];
	}

	getItemDetailData(result, currentDateField) {
		result = this.formatSearchResult(result);
		const formattedResult = {}

		//then add the most basic top level data
		formattedResult.resourceId = result._id;
		formattedResult.index = result._index;
		formattedResult.docType = result._type;
		formattedResult.collectionId = result.collectionId;

		formattedResult.rawData = result;
		formattedResult.title = this.__getTitel(result);
		formattedResult.description = this.__getDescription(result);

		const dateInfo = this.__getDateInfo(result);
		if(dateInfo) {
			formattedResult.date = dateInfo.date;
			formattedResult.dateField = dateInfo.field;
		}

		formattedResult.posterURL = this.__getPoster(result);

		const content = this.__extractPlayableContent(result);
		if(content) {
			formattedResult.playableContent = content.playableContent;
			formattedResult.mediaTypes = content.mediaTypes;
		}
		formattedResult.externalSourceInfo = {
			url : null,
			message : "View in Eye's catalog: No direct link, use the \"ID\" to search in the EYE collectie catalogus: https://www.eyefilm.nl/eye-catalogus-zoek-in-de-collectie"
		}
		formattedResult.searchReferences = this.__getSearchReferences(result);

		return formattedResult;
	}

	__getTitel(result) {
		if(result['Gegeven titel']) {
			return result['Gegeven titel'] + ' (given title)'
		} else if(result['Originele titel']) {
			return result['Originele titel'] + ' (original title)';
		} else if(result['Basement titel']) {
			return result['Basement titel'] + ' (basement title)';
		} else if(result['Nederlandse titel']) {
			return result['Nederlandse titel']  + ' (Dutch title)';
		}
		return 'Unknown'
	}

	__getDescription(result) {
		if(result['Korte beschrijving']) {
			return this.__normalizeStringOrArray(result['Korte beschrijving']);
		} else if(result['Lange beschrijving']) {
			return this.__normalizeStringOrArray(result['Lange beschrijving']);
		} else if(result['Inhoudsbeschrijving']) {
			return this.__normalizeStringOrArray(result['Inhoudsbeschrijving']);
		}
		return null;
	}

	__getDateInfo(result) {
		if(result['Productiejaar']) {
			return {
				date : this.__normalizeStringOrArray(result['Productiejaar']),
				field : 'Productiejaar'
			};
		} else if(result['Releasedatum']) {
			return {
				date : this.__normalizeStringOrArray(result['Releasedatum']),
				field : 'Releasedatum'
			};
		}
		return null;
	}

	__getPoster(result) {
		if (result['Url_efg_thumb']) {
			return this.__normalizeStringOrArray(result['Url_efg_thumb']);
		}
		return null;
	}

	__extractPlayableContent(result) {
		if(result.VideoId) {
			let playableContent = result.VideoId.split(', ').map(vid => {
				const videoId = vid + '.mp4';
				return {
					assetId : videoId,
					mimeType : 'video/mp4',
					url : _play +
						'/api/play/eye-video/' +
						this.__getContentId(videoId) +
						'?cid=' +
						_clientId +
						'&at=' +
						_chickenStock,
					contentId : this.__getContentId(videoId),
					contentServerId : 'eye-video',
					segments : null,
					isRawContent : false,
					playoutAccess : false // must be requested
				}
			});
			return {
				playableContent : playableContent,
				mediaTypes : ['video']
			}
		}
		return null;
	}

	__getContentId(videoId) {
		let parts = videoId.split('/');
		let contentId = parts.map((p) => {
			let i = p.length-1;
			let cid = '';
			while(i >= 0) {
				cid += String.fromCharCode(p.charCodeAt(i) + 1);
				i--;
			}
			return cid
		}).join('___');

		contentId = contentId.replace('/', '|||')
		return contentId
	}

	__getSearchReferences(result) {
		let searchRefs = {}; //KEY: Affiches, VALUE: list of {searchTerm, linkText} objects
 		if(result["Affiches"] && result["Affiches"] !== '') {
			searchRefs['Affiches'] = this.__parseAffiches(result['Affiches']);
 		}

 		if(result['Affiches (uit ander veld)']) {
			searchRefs['Affiches (uit ander veld)'] = this.__parseAffiches(result['Affiches (uit ander veld)']);
 		}
		return searchRefs != {} ? searchRefs : null;
	}

	//FIXME make sure to reimplement the link to search
	__parseAffiches(a) {
		const affiches = [];

		// Turn single object into an array
		if(!Array.isArray(a)) {
			a = [a];
		}
		a.forEach((line) => {
			let tmp = line.split(':');
			if(tmp.length > 1) {
				affiches.push({'searchTerm': tmp[0], 'linkText': line, 'collectionId': "eye-desmet-affiches"});
			}
		})
		return affiches;
	}

	//in case the field name cannot be found in the field descriptions
	formatIndexFieldName(esFieldName) {
		return esFieldName.replace(".keyword", "");
	}

	__normalizeStringOrArray(value) {
		if(typeof(value) === 'string') {
			return value;
		} else if(value.join) {
			return value.join('');
		}
		return null;
	}

}

export default EYEDesmetFilmConfig;
