import CollectionConfig from './CollectionConfig';

export class DANSOralHistoryConfig extends CollectionConfig {

	constructor(clientId, user, collectionId, collectionMetadata) {
		super(clientId, user, collectionId, collectionMetadata);
		// Filter the unnecessary fields...
		this.keywordFields = this.__filterKeywordFields();
	}

	requiresPlayoutAccess() {
		return true;
	}

	__filterKeywordFields() {
		const filteredFields = [];

		// Add the two default fields
		filteredFields.push('mediaType');
		filteredFields.push('playable');

		// Check for more options
		if(this.keywordFields) {
			for (let i = 0; i < this.keywordFields.length; i++) {
				//Must contain @graph and keyword and don't contain description, abstract or source (not useful facet fields)
				if (this.keywordFields[i].indexOf('@graph') !== -1 &&
						this.keywordFields[i].indexOf('keyword') !== -1 &&
						this.keywordFields[i].indexOf('description') === -1 &&
						this.keywordFields[i].indexOf('abstract') === -1 &&
						this.keywordFields[i].indexOf('source') === -1 ){
					filteredFields.push(this.keywordFields[i]);
				}
	    	}
	    }
		return filteredFields;
	}

	getMaximumYear() {
		return 2100;
	}

	getMetadataFieldCategories() {
		return [
			{
				id : 'titles',
				label : 'Titles',
				fields : [
					'@graph.dcterms:title'
				]
			},
			{
				id : 'descriptions',
				label : 'Descriptions',
				fields : [
					'@graph.dcterms:abstract'
				]
			},
			{
				id : 'subject metadata',
				label : 'Subject keywords',
				fields : [
					'@graph.dcterms:subject'
				]
			},
			{
				id : 'asr',
				label : 'Speech transcripts (ASR)',
				enrichment : true,
				fields : [
					'layer__asr.words'
				]
			}
		]
	}

	getFacets() {
		return [
            {
                field: 'mediaType',
                title : 'mediaType',
                id : 'mediaType',
                type : 'string'
            },
			{
				field: '@graph.dcterms:isPartOf.keyword',
				title: 'Oral history collection',
				id: 'thematic_collection',
				type: 'string'
			},
			{
				field: '@graph.dcterms:creator.keyword',
				title : 'Creator',
				id : 'creator',
				type : 'string'
			},
			{
				field: '@graph.dcterms:subject.keyword',
				title : 'Subject',
				id : 'subject',
				type : 'string'
			},
			{
				field: '@graph.dcterms:accessRights.keyword',
				title : 'Access rights',
				id : 'access_rights',
				type : 'string'
			},
			{
				field: '@graph.dcterms:format.keyword',
				title : 'Media format',
				id : 'media_format',
				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;

		if(result['@graph']) {
			formattedResult.title = this.__getTitle(result);
			formattedResult.description = result['@graph']['dcterms:abstract'];
			formattedResult.date = this.__getDate(result);
			formattedResult.dateField = '@graph.dcterms:created';
		}
		formattedResult.externalSourceInfo = this.__getExternalSourceInfo(result);
		if(result.playoutUrl) {

			let mediaObject = null;
			//format the verhalenhuis playoutURL so it is directed to the playout proxy
			if(result.playoutUrl.indexOf('file://') !== -1) {
				const audioId = result.playoutUrl.substring(7); //cut off file://
				mediaObject = {
					url : this.__toProxyUrl(audioId),
					mimeType : 'audio/wav',
					assetId : audioId.replace('.wav', ''),
					contentId : this.__getContentId(audioId),
					contentServerId : 'dans-verhalenhuis',
					playoutAccess : false //meaning it must be requested first
				}
			} else { //other links can be directly played
				mediaObject = {
					url : result.playoutUrl,
					mimeType : 'video/mp4',
					assetId : result._id,
					playoutAccess : true,
					requiresPlayoutAccess : false
				}
			}
			formattedResult.playableContent = [mediaObject]

			if(result['@graph']['dcterms:accessRights'] && result['@graph']['dcterms:accessRights'].length > 0 &&
				result['@graph']['dcterms:accessRights'].indexOf('OPEN_ACCESS') != -1) {
				//formattedResult.mediaTypes = ['video']
			}
		}
		formattedResult.mediaTypes = this.__determineMediaType(result);
		return formattedResult;
	}

	__determineMediaType(result) {
	    const mediaTypes = [];
	    let formats = null;
	    if(result.playoutUrl){
            formats = result.playoutUrl;
	    } else {
	        formats = result['@graph']['dcterms:format'];
	    }
	    if(formats){
            if(!Array.isArray(formats)){
                formats = [formats];
            }

            const audioRE = /AUDIO|SOUND|AIFF|MP3|WAV/;
            const videoRE = /MOV|264|MP4|AVI|MPEG|FLV|MXF|QUICKTIME|XD CAM|HDV/;

            formats.forEach(function(format) {
                if(audioRE.test(format.toUpperCase())){
                    if(mediaTypes.indexOf("audio") === -1) {
                        mediaTypes.push("audio");
                    }
                }
                if(videoRE.test(format.toUpperCase())){
                    if(mediaTypes.indexOf("video") === -1) {
                        mediaTypes.push("video");
                    }
                }
            });
            if(mediaTypes.length == 0){
                return ['text'];
            }
            return mediaTypes;
	    } else {
	        return ['text'];
	    }
	}

	__getTitle(result) {
		const title = result['@graph']['dcterms:title'];
		if(title) {
			if(typeof(title) === 'string') {
				return result['@graph']['dcterms:title'];
			} else {
				return result['@graph']['dcterms:title'].join('; ');
			}
		}
		return null;
	}

	__getDate(result) {
		const dc = result['@graph']['dcterms:created'];
		if(dc) {
			if(typeof(dc) === 'string') {
				return result['@graph']['dcterms:created'];
			} else {
				return result['@graph']['dcterms:created'].join('; ');
			}
		}
		return null;
	}

	__getExternalSourceInfo(result) {
		const source = 'https://easy.dans.knaw.nl/ui/rest/datasets/easy-dataset';
		if(result._id && result._id.lastIndexOf(':') !== -1) {
			return {
				url : source + result._id.substring(result._id.lastIndexOf(':')),
				message : null
			}
		}
		return null;
	}

    // Date formats accepted are either:
    // date: "2009-09-20; 2009-03-21"
    // date: "2010-03-21"
    // date: "2008"
    // date: "1984; 1983"
    // date" "1984; 1983; 2009-11-02"
    // date: "2009-05-20; 2008-08-30; 2009-05-22"
    // check if there's a ; meaning more than one date
    // It returns the earliest date (from a string containing 1 or more dates) as a Timestamp or null
    getFormattedDates(date) {
        if (date && typeof(date) === 'string') {
            if (date.trim().indexOf(';') !== -1) {
                return date.split(';').map(it => it.trim());
            } else {
                return [date.trim()];
            }
        }
        return null;
    }

    //in case the field name cannot be found in the field descriptions
    formatIndexFieldName(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));

            //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') {
                tmp.pop();
            }

			return tmp.pop();
        }
    }

    /* ---------------------- FOR THE VERHALENHUIS VIDEOS ONLY (TEMPORARY SOLUTION) ---------------------- */

    __toProxyUrl(videoId) {
    	return _play +
		'/api/play/dans-verhalenhuis/' +
		this.__getContentId(videoId) +
		'?cid=' +
		_clientId +
		'&at=' +
		_chickenStock
    }

    __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
	}

}

export default DANSOralHistoryConfig;
