import CollectionConfig from './CollectionConfig';

export class NISVProgramGuideBlockConfig extends CollectionConfig {
	constructor(clientId, user, collectionId, collectionMetadata) {
		super(clientId, user, collectionId, collectionMetadata);
	}

	getNamespace() {
		return 'omroepgidsen.beeldengeluid.nl/';
	}

	getCollectionMediaTypes() {
		return ['image', 'text'];
	}

	//we want to search based on this granularity
	getFragmentPath() {
		return 'pages.blocks';
	}

	//this is the text field you can search on the line level
	getFragmentTextFields() {
		return ['pages.blocks.words'];
	}

	getFieldsToExclude() {
		return null;
	}

	requiresPlayoutAccess() {
		return true;
	}

	getThumbnailContentServerId() {
		return 'beng-image';
	}

	getFacets() {
		return [
			{
				field: 'broadcaster',
				title: 'Omroep',
				id: 'broadcaster',
				type : 'string'
			},
			{
				field: 'year',
				title: 'Jaar',
				id: 'year',
				type : 'integer'
			},
			{
				field: 'date',
				title: 'Datum',
				id: 'date',
				type : 'date_histogram'
			}
		];
	}

	//TODO if available add the poster URL:
	//http://jaws.beeldengeluid.nl/fastcgi-bin/iipsrv.fcgi?IIIF=omroepgidsen/1971/EO/EO1971-02_008.tif/1036,1366,693,1366/full/0/default.jpg
	getItemDetailData(result, currentDateField) {
		//first flatten the pure ES response
		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.rawData = result;

		//taken from the parent doc
		formattedResult.title = result.title;
		formattedResult.date = result.date;
		formattedResult.dateField = result.dateField;

		//taken from the block part

		formattedResult.description = result.words;

		const contentId = this.__getContentId(result.imageUrl);
		if(contentId) {
			formattedResult.posterURL = this.__getPosterURL(result, contentId);
			if(result._type == 'media_fragment') {
				formattedResult.mediaFragment = this.__toMediaFragment(
					result.imageUrl, result._id
				);
			}
		}

		//all the different pages
		formattedResult.playableContent = this.__getPlayableContent(result);

		return formattedResult;
	}

	__toMediaFragment(url, resourceId) {
		if(url) {
			const temp = url.split('/');
			const coords = temp[temp.length - 4].split(',');
			const imageFile = temp[temp.length - 5];
			const pageNr = parseInt(imageFile.substring(imageFile.length -7, imageFile.length -4));
			return {
				assetId : this.getNamespace() + resourceId + '/' + pageNr,
				x : coords[0],
				y : coords[1],
				w : coords[2],
				h : coords[3],
			}
		}
		return null;
	}

	__getPosterURL(result, contentId) {
		if(result.imageUrl) {
			let imgUrl = _play + '/api/play/beng-image/' + contentId;
			imgUrl += this.__extractIIIFCoordinates(result.imageUrl);
			imgUrl += '/pct:50/0/default.jpg';
			return imgUrl;
		}
		return null
	}

	__extractIIIFCoordinates(url) {
		if(url && url.indexOf('.tif') != -1) {
			return url.substring(
				url.indexOf('.tif') + 4,
				(url.length - '/full/0/default.jpg'.length)
			)
		}
		return 'full'
	}

	//TODO this should only be fetched on the item detail page!
	__getPlayableContent(result) {
		let playableContent = [];
		if(result.pages && result.pages.forEach) {
			let contentId = null;
			result.pages.forEach(page => {
				if(page.imageUrl) {
					contentId = this.__getContentId(page.imageUrl);
					if(contentId) {
						playableContent.push({
							//url : page.imageUrl.replace('pct:0,0,100,100', 'full'), //make sure this is /full/full
							url :  _play +
								'/api/play/beng-image/' +
								contentId +
								'/info.json',
							mimeType : 'image/jpeg',
							assetId : this.getNamespace() + result._id + '/' + page.pageNumber, //is this a good asset ID?
							contentId : this.__getContentId(page.imageUrl),
							contentServerId : 'beng-image'
						})
					}
				}
			})
		}
		return playableContent.sort((a,b) => {
			return a.assetId - b.assetId;
		});
	}

	//"http://jaws.beeldengeluid.nl/fastcgi-bin/iipsrv.fcgi?IIIF=omroepgidsen/2011/NCRV/NCRV2011-44_099.tif/pct:0,0,100,100/full/0/default.jpg",
	__getContentId(imageUrl) {
		if(imageUrl) {
			const i1 = imageUrl.indexOf('IIIF=') + 'IIIF='.length;
			const i2 = imageUrl.indexOf('.tif')// + '.tif'.length;
			const contentPath = imageUrl.substring(i1,i2)
			let parts = contentPath.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
		}
		return null;
	}

}

export default NISVProgramGuideBlockConfig;