class ez5.PdfCreator.Header extends CUI.Element

	initOpts: ->
		super()
		@addOpts
			data:
				check: "PlainObject"
				default: {}

	readOpts: ->
		super()
		@__data = @_data
		for position in ["left", "center", "right"]
			if @__data[position]
				continue
			@__data[position] = {}
		return @

	getData: ->
		return @__data

	# Header is a special case babuse it can return a promise.
	# In the header we need base64 images, so we need to load the images and convert to base64 first
	renderPdfContent: (opts) ->
		# In header we can have image, but the pdf-renderer only support images as base64 in header
		# so if we have images in any position of the header we load the images and convert to base64
		if not opts.header_loaded and not opts.preview
			loadPromises = []
			for position in ["left", "center", "right"]
				do (position) =>
					if @__data[position].type == "image" and @__data[position]["file:eas_file"]?._id
						# First we need to load the EAS
						@__imagesData ?= {}
						easID = @__data[position]["file:eas_file"]?._id
						if @__imagesData[easID]
							return
						imagePromise = new CUI.Deferred()
						ez5.api.eas
							type: "GET"
							data:
								ids: JSON.stringify([easID])
								format: "long"

						.done((easData) =>
							imageRequest = new CUI.XHR
								method: "GET"
								url: Session.addToken(easData[easID]?.versions?.original?.url)
								responseType: "blob"
							imageRequest.start().done( (blob) =>
								fileReader = new FileReader()
								fileReader.readAsDataURL(blob)
								fileReader.onloadend = =>
									@__imagesData[easID] = fileReader.result # Base64 data.
									imagePromise.resolve()
							)
						)
						loadPromises.push(imagePromise.promise())

			if loadPromises.length > 0
				dfr = new CUI.Deferred()
				CUI.whenAll(loadPromises).done =>
					opts.header_loaded = true
					return dfr.resolve(@renderPdfContent(opts))
				return dfr.promise()


		header = CUI.dom.div("pdf-node-#{@constructor.name.toLowerCase()}")

		if not opts.preview
			# Specific measures for printing.
			CUI.dom.setStyle(header,
				"font-size": "8px"
				"padding-left": "0.28in"
				"padding-right": "0.28in"
				"width": "calc(100% - 0.56in)"
			)

		data = @getData()
		for position in ["left", "center", "right"]
			div = CUI.dom.div()
			CUI.dom.append(header, div)

			CUI.dom.setStyle(div,
				"display": "inline-block"
				"text-align": position
				"min-height": if opts.preview then "12px" else "8px"
			)

			_data = data[position]
			switch _data.type
				when "logo"
					if not ez5.PdfCreator.logoImage
						continue

					CUI.dom.setStyle(div,"min-height": 0)

					# For now we use the base config logo in Base64.
					img = CUI.dom.element("img", src: ez5.PdfCreator.logoImage)
					imgDiv = CUI.dom.div("pdf-node-header-image-#{position}")
					CUI.dom.append(imgDiv, img)

					if not opts.preview
						# Specific measures for printing.
						CUI.dom.setStyle(img,
							"height": "0.3in"
						)

					CUI.dom.append(div, imgDiv)
				when "image"
					# For printing we use the base64 images.
					if not opts.preview
						CUI.dom.setStyle(div,"min-height": 0)
						easID = _data["file:eas_file"]?._id
						img = CUI.dom.element("img", src: @__imagesData[easID])
						imgDiv = CUI.dom.div("pdf-node-header-image-#{position}")
						CUI.dom.append(imgDiv, img)
						# Specific measures for printing.
						CUI.dom.setStyle(img,
							"height": "0.3in"
						)
					else
						# For preview we use normal url images.
						if not _data["file:eas_file"]?._id
							continue
						asset = new AssetPlain(value: _data["file:eas_file"])
						imgDiv = CUI.dom.div("pdf-node-header-image-#{position}")
						assetImg = asset.getImgElement(null, "original", for_print: true)
						imgEl = assetImg.querySelector("img")
						if imgEl
							CUI.dom.append(imgDiv, imgEl)
						else
							CUI.dom.append(imgDiv, assetImg)

					CUI.dom.append(div, imgDiv)
				else
					text = ez5.loca.getBestFrontendValue(_data.text)
					if not text
						continue

					CUI.dom.setStyle(div,
						"white-space": "nowrap"
						"overflow": "hidden"
					)

					text = text.replace(/%pageNumber%/g, "<span class='pageNumber'>1</span>")
					text = text.replace(/%totalPages%/g, "<span class='totalPages'>#{opts.objects?.length or 1}</span>")

					object = opts.objects[0] # Use the first object, even if it is multiple objects (grid)
					text = ez5.PdfCreatorUtils.replaceTextPlaceholders(text, object)

					textNodes = CUI.dom.htmlToNodes(text)
					CUI.dom.append(div, textNodes)

		# When the center div is empty, left and right widths are 50%, otherwise 33%.
		centerDiv = header.children[1]
		if not centerDiv.hasChildNodes()
			centerDiv.remove()

		children = CUI.dom.children(header)
		width = 100 / children.length
		for node in children
			CUI.dom.setStyle(node, "width": "#{width}%")
		return header

	getSettingsFields: (opts = {}) ->
		getFields = (position) =>
			textHintButton = new CUI.Button
				text: $$("pdf-creator.settings.node.header.text|hint")
				appearance: "flat"
				onClick: =>
					pop = new ez5.HintPopover
						element: textHintButton
						content: new CUI.Label(text: $$("pdf-creator.settings.node.header.text.popover"), markdown: true)
						padded: true
					pop.show()

			textField =
				type: CUI.MultiInput
				form:
					label: $$("pdf-creator.settings.node.header.text|label")
					hint: textHintButton
				control: ez5.loca.getLanguageControl()
				name: "text"

			eas_field = new EASField
				name: "file:eas_file"
			customImageField =
				type: CUI.DataFieldProxy
				form: label: $$("pdf-creator.settings.node.eas.file")
				name: "file:eas_file"
				element: (df) =>
					eas_field.renderEditorInput(df.getData(), null)

			if position == "center" or not @__supportsLogo()
				return [textField]

			onDataChanged = (data, field) ->

				form = field.getForm()
				textField = form.getFieldsByName("text")[0]
				customImageField = form.getFieldsByName("file:eas_file")[0]

				switch data.type
					when "logo"
						textField.hide(true)
						customImageField.hide(true)
					when "text"
						textField.show(true)
						customImageField.hide(true)
					else
						textField.hide(true)
						customImageField.show(true)

				return

			logoFieldDisabled = not ez5.PdfCreator.logoImage
			if logoFieldDisabled
				logoText = $$("pdf-creator.settings.node.header.select.option-logo-disabled|label")
			else
				logoText = $$("pdf-creator.settings.node.header.select.option-logo|label")

			formFields = [
				type: CUI.Select
				name: "type"
				form:
					label: $$("pdf-creator.settings.node.header.select|label")
				options: [
					text: $$("pdf-creator.settings.node.header.select.option-text|label")
					value: "text"
				,
					text: logoText
					value: "logo"
					disabled: logoFieldDisabled
				,
					text: $$("pdf-creator.settings.node.header.select.option-image|label")
					value: "image"
				]
				onDataInit: (field, data) -> onDataChanged(data, field)
				onDataChanged: onDataChanged
			,
				textField
			,
				customImageField
			]

			return formFields

		forms = []
		for position in ["left", "center", "right"]
			forms.push
				type: CUI.Form
				form: label: $$("pdf-creator.settings.node.header.title.#{position}|label")
				render_as_block: true
				name: position
				fields: getFields(position)
				data: @getData()

		return forms

	# Enable/Disable logo in the settings.
	__supportsLogo: ->
		return true

	getSaveData: ->
		data = @getData()
		for position in ["left", "center", "right"]
			if CUI.util.isEmpty(data[position]["file:eas_file"])
				# Remove empty EAS file data. Server expect no data for empty eas_files
				delete data[position]["file:eas_file"]
		return CUI.util.copyObject(@getData(), true)