<%
	// CREATE ALIASES
	const language = locals.metadata.page.language
	include ('../../partials/translations.ejs')
%>
<script type='text/javascript'>

const include_incomplete = false

function addPrintSection (kwargs) {
	return new Promise(async resolve => {
		const { data, lang, article } = kwargs || {}
		let { id, title, lead, structure, items, repeat, group, instruction } = data || {}
		
		if (!title) title = ''
		if (!lead) lead = ''
		if (!structure) structure = []
		if (!items) items = []

		if (templated && !items.length && include_incomplete) items = JSON.parse(JSON.stringify(structure))

		const section = article.append('section', 'media-layout layout print')
			.classed('repeat', repeat || false)
			.datum({ id, type: 'section', title, lead, structure, items, repeat, group })

		const header = section.addElems('h1', 'section-header', d => {
			if (d.title?.length === 0) return []
			else return [d]
		}).html(d => d.title)

		if (templated && lead) {
			section.addElem('p', 'lead')
			.html(lead)
		}

		if (items.length) {
			const promises = []
			section.each(function (d) {
				promises.push(d.items.map(async c => await populatePrintSection (c, lang, this)))
			})
			await Promise.all(promises.flat())
		}

		resolve(section.node())
	})
}
function populatePrintSection (data, lang = 'en', section) {
	// MEDIA
	return new Promise(async resolve => {
		// if (data.type === 'title' && publicpage) addTitle({ data, lang, section }) // TO DO
		if (data.type === 'img') addPrintImg({ data, lang, section })
		if (data.type === 'mosaic') addPrintMosaic({ data, lang, section })
		// if (data.type === 'video') addVideo({ data, lang, section }) // CANNOT DISPLAY VIDEOS IN PRINT
		if (data.type === 'drawing') addDrawing({ data, lang, section }) // TO DO
		
		if (data.type === 'txt') addPrintTxt({ data, lang, section })
		if (data.type === 'embed') addPrintEmbed({ data, lang, section })
		if (data.type === 'checklist') addPrintList({ data, lang, section })
		if (data.type === 'radiolist') addPrintList({ data, lang, section })
		// META
		if (data.type === 'location') await addPrintLocations({ data, lang, section }) // TO DO: NEED REVERSE GEOCODING
		if (data.type === 'index') addPrintIndexes({ data, lang, section })
		if (data.type === 'tag') addPrintTags({ data, lang, section })
		
		// if (data.type === 'attachment') addAttachment({ data, lang, section }) // TO DO
		
		// GROUP
		if (data.type === 'group') await addPrintGroup({ data, lang, section })

		resolve()
	})
}

function addPrintImg (kwargs) {
	const { data, lang, section } = kwargs || {}
	let { name, src, scale, instruction } = data || {}

	if (!name) name = null
	if (!src) src = null
	if (!scale) scale = 'original'

	if (src?.length === 0 && !include_incomplete) return null

	const parent = d3.select(section)
	if (instruction) {
		parent.addElem('p', 'instruction')
		.html(instruction)
	}

	parent.addElem('img')
		.attrs({
			'src': src?.isURL() ? src : `/${src}`,
			'class': scale,
			'alt': 'missing image' // TO DO: TRANSLATE
		})
}
function addPrintMosaic (kwargs) {
	const { data, lang, section } = kwargs || {}
	let { name, srcs, verticalalign, instruction } = data || {}
	
	if (!name) name = null
	if (!srcs) srcs = []
	if (!verticalalign) verticalalign = 'center'


	if (srcs?.length === 0 && !include_incomplete) return null

	const parent = d3.select(section)
	if (instruction) {
		parent.addElem('p', 'instruction')
		.html(instruction)
	}
	
	parent.addElem('div', 'mosaic')
		.datum(_ => {
			return srcs?.length ? srcs : []
		}).classed('x2', srcs.length < 3)
		.style('align-items', verticalalign)
	.addElems('img', 'mosaic-item', d => d)
		.attrs({
			'src': d => d?.isURL() ? d : `/${d}`,
			'alt': 'missing image' // TO DO: TRANSLATE
		})
}
function addPrintTxt (kwargs) {
	const { data, lang, section } = kwargs || {}
	let { name, fontsize, fontweight, fontstyle, textalign, txt, instruction } = data || {}

	if (!name) name = null
	if (!fontsize) fontsize = 1
	if (!fontweight) fontweight = 'normal'
	if (!fontstyle) fontstyle = 'normal'
	if (!textalign) textalign = 'left'
	if (!txt) txt = ''
	if (typeof txt !== 'string') txt = txt.toString()

	if (txt?.trim().length === 0 && !include_incomplete) return null

	const parent = d3.select(section)
	if (instruction) {
		parent.addElem('p', 'instruction')
		.html(instruction)
	}

	parent.addElem('p')
	.styles({	
		'min-height': `${fontsize}rem`, 
		'font-size': `${fontsize}rem`, 
		'line-height': `${fontsize * 1.35}rem`,
		'font-weight': fontweight,
		'font-style': fontstyle,
		'text-align': textalign 
	}).html(txt.convertHTMLtoTXT())
}
function addPrintEmbed (kwargs) {
	const { data, lang, section } = kwargs || {}
	let { name, textalign, html, src, instruction } = data || {}
	
	if (!name) name = null
	if (!textalign) textalign = 'left'
	if (!html) html = ''
	if (!src) src = null

	if ((html?.trim().length === 0 || src?.length === 0) && !include_incomplete) return null

	const parent = d3.select(section)
	if (instruction) {
		parent.addElem('p', 'instruction')
		.html(instruction)
	}

	parent.addElem('p', 'embedding')
	.style('text-align', textalign)
		.html(d => {
			// TO DO: SOMETHING IF iframe

			// if (!editing && d.html.trim().isURL()) return `<a href=${d.html.trim()} target='_blank'>${d.html}</a>`
			// else return d.html
			return html.convertHTMLtoTXT()
		})
}
function addPrintList (kwargs) { 
	const { data, lang, section } = kwargs || {}
	let { name, fontsize, fontweight, fontstyle, options, instruction } = data || {}
	
	if (!name) name = null
	if (!fontsize) fontsize = 1
	if (!fontweight) fontweight = 'normal'
	if (!fontstyle) fontstyle = 'normal'
	if (!options) options = []
	else {
		// THIS IS SO THAT ANY NULL OPTION (THAT MIIGHT COME FROM AN EXCEL SHEET) GETS PUSHED TO THE END
		options = options.filter(d => d.name)
		options.sort((a, b) => {
			if (a.name === b.name) return 0
			else if (!a.name || !a.name.trim().length) return 1
			else if (!b.name || !b.name.trim().length) return -1
			else return a.id < b.id ? -1 : 1
		})
	}

	if (options?.filter(d => d.checked).length === 0 && !include_incomplete) return null

	const parent = d3.select(section)
	if (instruction) {
		parent.addElem('p', 'instruction')
		.html(instruction)
	}

	const list = parent.addElem('ol')
		.styles({	
			'min-height': `${fontsize}rem`, 
			'font-size': `${fontsize}rem`, 
			'line-height': `${fontsize * 1.35}rem`,
			'font-weight': fontweight,
			'font-style': fontstyle
		})
	.addElems('li', 'opt', options)
		.classed('checked', d => d.checked)
		.html(d => d.name)
}
// META ELEMENTS
function addPrintLocations (kwargs) {
	return new Promise(async resolve => {
		// TO DO: INCLUDE CONSTRAINT
		const { data, lang, section } = kwargs || {}
		let { name, instruction, centerpoints } = data || {}
		
		if (!name) name = null
		if (!centerpoints) centerpoints = []

		if (centerpoints?.length === 0 && !include_incomplete) return null

		const results = await POST('/reverseGeocoding', { locations: centerpoints.map(d => [d.lat, d.lng]), list: true })
				
		if (results[0].found) {
			const parent = d3.select(section)
			if (instruction) {
				parent.addElem('p', 'instruction')
				.html(instruction)
			}

			parent.addElem('ul', 'locations')
				.datum(_ => {
					return results?.length ? results : []
				}).addElems('li', 'location', d => d)
					.html(d => d.formatted)

					// listContainer.select('.lds-ellipsis').remove()
			
			parent.addElem('p', 'caption')
				.html(results[0].caption)
		}
		resolve()
	})
}
function addPrintIndexes (kwargs) {
	const { data, lang, section } = kwargs || {}
	let { name, instruction, tags } = data || {}

	if (!name) name = null
	if (!tags) tags = [] 
	// MAKE SURE THE SDGs ARE SORTED BY key
	tags.sort((a, b) => a.key - b.key)

	if (tags?.length === 0 && !include_incomplete) return null

	const parent = d3.select(section)
	if (instruction) {
		parent.addElem('p', 'instruction')
		.html(instruction)
	}

	const promises = []
	parent.addElem('ol', 'indexes')
		.datum(_ => {
			return tags?.length ? tags : []
		}).addElems('li', 'index', d => d)
	.each(function (d) { d3.select(this).classed(d.type, true) })
		.addElem('img')
		.attrs({ 
			'src': d => `/imgs/sdgs/${lang}/G${d.key || d}-c.svg`,
			'alt': d => d.name 
		})
}
function addPrintTags (kwargs) {
	const { data, lang, section } = kwargs || {}
	let { name, instruction, tags } = data || {}
	
	if (!name) name = null
	if (!tags) tags = []

	if (tags?.length === 0 && !include_incomplete) return null

	const parent = d3.select(section)
	if (instruction) {
		parent.addElem('p', 'instruction')
		.html(instruction)
	}

	parent.addElem('ul', 'tags')
		.datum(_ => {
			return tags?.length ? tags : []
		}).addElems('li', 'tag', d => d)
	.each(function (d) { d3.select(this).classed(d.type, true) })
		.html(d => d.name)
}
// GROUPS
function addPrintGroup (kwargs) {
	return new Promise(async resolve => {
		const { data, lang, section } = kwargs || {}
		let { name, items, instruction, repeat } = data || {}
		if (!name) name = null
		if (!items) items = []

		const promises = []
		items.forEach(function (d) {
			promises.push(d.map(async c => {
				await populatePrintSection (c, lang, section)
			}))
		})
		await Promise.all(promises.flat())
		resolve()
	})
}


// // TO DO: POPULATE THE PAGE IN A MUCH SIMPLER LAYOUT
// class MyHandler extends Paged.Handler { 
// 	// CHECK DOC HERE: https://pagedjs.org/documentation/10-handlers-hooks-and-custom-javascript/
// 	constructor(chunker, polisher, caller) {
// 		super(chunker, polisher, caller);
// 	}

// 	async beforeParsed(content) {
// 		console.log(content)
		
// 		const data = <%- JSON.stringify(locals.data || {}) %>;
// 		return Promise.all(data.sections.map(async d => {
// 			await addPrintSection({ data: d, lang: '<%- language %>' })
// 		}))

// 	}
// }
// Paged.registerHandlers(MyHandler);

</script>