// form/nc/nc-document/nc-document.js

let selectedDocType = ref('')
let pdfFrame = null
let pdfFullscreenFunc = null
let documentPassword = {}
const cache = {
	// cache last loaded document data, saves rest call
	// todo: cache all files in view?
	docData: null,
	docPath: '',
	docName: '',
	docType: '',
	mimeType: ''
}

function clearPreview(clearName) {
	if (clearName) {
		rec.document_name = ''
	}
	rec.document_style = 'display: none'
	nc.setRec(state, 'document_data', { data: '', viewer_show_type: 'preview', mime_type: '', document_name: '' })
}

// eslint-disable-next-line no-unused-vars
function fullScreen() {
	if (pdfFrame == null) {
		pdfFrame = document.getElementById('pdfjs-viewer-iframe')
		pdfFullscreenFunc = pdfFrame.requestFullscreen || pdfFrame.webkitRequestFullscreen || pdfFrame.mozRequestFullScreen
	}
	if (pdfFullscreenFunc) {
		pdfFullscreenFunc.call(pdfFrame)
	}
}

// eslint-disable-next-line no-unused-vars
function closeFullpage() {
	rec.document_style = rec.document_style_preview
	rec.viewer_show_type = 'preview'
	documentRowClicked(rec.viewer_show_type)
}

function find() {
	nc.callServer(
		state,
		'form/nc/nc-document',
		{
			parameter: {
				connection: rec.connection,
				state: rec.document_state,
				product: rec.product
			}
		},
		() => {
			documentPassword = {}
			if (rec.select_row_on_load) {
				setTimeout(() => {
					const unselectOther = true
					const scroll = true
					nc.grid.activateRows(state, 'document', 1, scroll, unselectOther)
					documentRowClicked(rec.viewer_show_type)
				}, rec.select_row_timeout) // needs timeout for grid to be drawn
			}
		}
	)
}

function openCallback(ret, showType) {
	let docData = ret.rec && ret.rec.picture // must use re.rec because of keep_value in rest answer
	if (!docData) {
		// show error message?
		clearPreview()
		return
	}
	const docName = rec.document_name
	const docPath = rec.document_path
	let docType = rec.document_type.toLowerCase()
	openDocument(showType, docName, docPath, docData, docType)
}

function openDocument(showType, docName, docPath, docData, docType) {
	message.clearMessage(state) // clear old errors on successful load
	let mimeType // see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
	if (docType === 'txt' || docType === 'text') {
		// docType = 'text'
		mimeType = 'text/plain'
	} else if (docType === 'md') {
		mimeType = 'text/markdown'
	} else if (docType === 'csv' || docType === 'css' || docType === 'html' || docType === 'javascript') {
		mimeType = 'text/' + docType
	} else if (docType === 'svg') {
		mimeType = 'image/svg+xml'
	} else if (docType === 'jpg') {
		mimeType = 'image/jpeg'
	} else if (docType === 'png' || docType === 'jpeg' || docType === 'gif' || docType === 'webp' || docType === 'avif') {
		mimeType = 'image/' + docType
	}
	if (!mimeType) {
		mimeType = 'application/' + docType
	} else if (!rec.open_type.includes(docType) && !rec.open_type.includes(mimeType)) {
		const txt = nc.l(`document type '${mimeType}' can not be opened`)
		message.alert(state, txt)
		return
	}
	/* const save = false
			if (save) {
				// or nc.isSafari()
				lib.saveFileAs(blob, docName)
			} else { */
	if (cache.docPath !== docPath) {
		cache.docData = docData
		cache.docPath = docPath
		cache.docName = docName
		cache.docType = docType
		cache.mimeType = mimeType
	}
	if (docType === 'pdf') {
		if (showType === 'fullpage') {
			rec.document_style = rec.document_style_fullpage
		} else {
			rec.document_style = rec.document_style_preview
		}
	}
	nc.setRec(state, 'viewer_show_type', showType)
	nc.setRec(state, 'document_data', { data: docData, viewer_show_type: showType, mime_type: mimeType, document_name: docName })
	// }
}

// eslint-disable-next-line no-unused-vars
function passwordCallback(reason) {
	let answer
	if (reason === 1) {
		if (documentPassword[rec.document_name]) {
			return documentPassword[rec.document_name]
		}
		answer = prompt(nc.l(`Please enter pdf password`))
	} else {
		// if (reason === 2) {
		answer = prompt(nc.l(`Entered password was invalid, please enter pdf password`))
		/* } else {
				answer = prompt(nc.l(`Please enter pdf password (reason: ${reason})`)) */
	}
	documentPassword[rec.document_name] = answer
	return answer
}

function documentRowClicked(showType) {
	const arr = nc.grid.activatedRecordArr(state, 'document')
	clearPreview(false)
	if (arr && arr.length > 0) {
		const row = arr[0]
		if (row.value === cache.docPath) {
			openDocument(showType, cache.docName, cache.docPath, cache.docData, cache.docType, cache.mimeType)
		} else {
			if (row.value !== '') {
				selectedDocType.value = row.field_type
				if (!selectedDocType.value) {
					// empty string
					selectedDocType.value = peg.parseAfterLast(row.value, '.')
				}
				selectedDocType.value = selectedDocType.value.toLowerCase()
				const param = {
					connection: rec.connection,
					state: rec.document_state,
					document_name: row.info,
					document_path: row.value,
					document_type: selectedDocType.value,
					max_file_size_kb: rec.max_file_size_kb
				}
				nc.callServer(state, 'form/nc/nc-document', { parameter: param }, ret => {
					return openCallback(ret, showType)
				})
			}
		}
	}
}

clearPreview()
if (rec.product !== '') {
	find()
}
