<template>
	<div class="editor">
		<div class="clear"></div>

		<vue-easymde
			:configs="config"
			@change="() => bubbleNow()"
			@update:modelValue="handleInput"
			class="content"
			v-if="isEditActive"
			v-model="text"/>

		<div class="preview content" v-html="preview" v-if="isPreviewActive && text !== ''">
		</div>

		<p class="has-text-centered has-text-grey is-italic my-5" v-if="showPreviewText">
			{{ emptyText }}
			<template v-if="isEditEnabled">
				<ButtonLink
					@click="toggleEdit"
					v-shortcut="editShortcut"
					class="d-print-none">
					{{ $t('input.editor.edit') }}
				</ButtonLink>.
			</template>
		</p>

		<ul class="actions d-print-none" v-if="bottomActions.length > 0">
			<li v-if="isEditEnabled && !showPreviewText && showSave">
				<BaseButton
					v-if="showEditButton"
					@click="toggleEdit"
					v-shortcut="editShortcut">
					{{ $t('input.editor.edit') }}
				</BaseButton>
				<BaseButton
					v-else-if="isEditActive"
					@click="bubbleSaveClick"
					class="done-edit">
					{{ $t('misc.save') }}
				</BaseButton>
			</li>
			<li v-for="(action, k) in bottomActions" :key="k">
				<BaseButton @click="action.action">{{ action.title }}</BaseButton>
			</li>
		</ul>
		<template v-else-if="isEditEnabled && showSave">
			<ul v-if="showEditButton" class="actions d-print-none">
				<li>
					<BaseButton
						@click="toggleEdit"
						v-shortcut="editShortcut">
						{{ $t('input.editor.edit') }}
					</BaseButton>
				</li>
			</ul>
			<x-button
				v-else-if="isEditActive"
				@click="bubbleSaveClick"
				variant="secondary"
				:shadow="false"
				v-cy="'saveEditor'">
				{{ $t('misc.save') }}
			</x-button>
		</template>
	</div>
</template>

<script setup lang="ts">
import {computed, nextTick, onMounted, ref, toRefs, watch} from 'vue'

import VueEasymde from './vue-easymde.vue'
import {marked} from 'marked'
import DOMPurify from 'dompurify'

import {createEasyMDEConfig} from './editorConfig'

import AttachmentModel from '@/models/attachment'
import AttachmentService from '@/services/attachment'

import {setupMarkdownRenderer} from '@/helpers/markdownRenderer'
import {findCheckboxesInText} from '@/helpers/checklistFromText'
import {createRandomID} from '@/helpers/randomId'

import BaseButton from '@/components/base/BaseButton.vue'
import ButtonLink from '@/components/misc/ButtonLink.vue'
import type {IAttachment} from '@/modelTypes/IAttachment'
import type {ITask} from '@/modelTypes/ITask'

const props = defineProps({
	modelValue: {
		type: String,
		default: '',
	},
	placeholder: {
		type: String,
		default: '',
	},
	uploadEnabled: {
		type: Boolean,
		default: false,
	},
	uploadCallback: {
		type: Function,
	},
	hasPreview: {
		type: Boolean,
		default: true,
	},
	previewIsDefault: {
		type: Boolean,
		default: true,
	},
	isEditEnabled: {
		default: true,
	},
	bottomActions: {
		type: Array,
		default: () => [],
	},
	emptyText: {
		type: String,
		default: '',
	},
	showSave: {
		type: Boolean,
		default: false,
	},
	// If a key is passed the editor will go in "edit" mode when the key is pressed.
	// Disabled if an empty string is passed.
	editShortcut: {
		type: String,
		default: '',
	},
})

const emit = defineEmits(['update:modelValue', 'save'])

const text = ref('')
const isEditActive = ref(false)
const isPreviewActive = ref(true)

const showPreviewText = computed(() => isPreviewActive.value && text.value === '' && props.emptyText !== '')
const showEditButton = computed(() => !isEditActive.value && text.value !== '')

const preview = ref('')
const attachmentService = new AttachmentService()

type CacheKey = `${ITask['id']}-${IAttachment['id']}`
const loadedAttachments = ref<{ [key: CacheKey]: string }>({})
const config = ref(createEasyMDEConfig({
	placeholder: props.placeholder,
	uploadImage: props.uploadEnabled,
	imageUploadFunction: props.uploadCallback,
}))

const checkboxId = ref(createRandomID())

const {modelValue} = toRefs(props)

watch(
	modelValue,
	async (value) => {
		text.value = value
		await nextTick()
		renderPreview()
	},
)

watch(
	text,
	(newVal, oldVal) => {
		// Only bubble the new value if it actually changed, but not if the component just got mounted and the text changed from the outside.
		if (oldVal === '' && text.value === modelValue.value) {
			return
		}
		bubbleNow()
	},
)


onMounted(() => {
	if (modelValue.value !== '') {
		text.value = modelValue.value
	}

	if (props.previewIsDefault && props.hasPreview) {
		nextTick(() => renderPreview())
		return
	}

	isPreviewActive.value = false
	isEditActive.value = true
})


// This gets triggered when only pasting content into the editor.
// A change event would not get generated by that, an input event does.
// Therefore, we're using this handler to catch paste events.
// But because this also gets triggered when typing into the editor, we give
// it a higher timeout to make the timouts cancel each other in that case so
// that in the end, only one change event is triggered to the outside per change.
function handleInput(val: string) {
	// Don't bubble if the text is up to date
	if (val === text.value) {
		return
	}

	text.value = val
	bubbleNow()
}

function bubbleNow() {
	emit('update:modelValue', text.value)
}

function replaceAt(str: string, index: number, replacement: string) {
	return str.slice(0, index) + replacement + str.slice(index + replacement.length)
}

function findNthIndex(str: string, n: number) {
	const checkboxes = findCheckboxesInText(str)
	return checkboxes[n]
}

function renderPreview() {
	setupMarkdownRenderer(checkboxId.value)

	preview.value = DOMPurify.sanitize(marked(text.value), {ADD_ATTR: ['target']})

	// Since the render function is synchronous, we can't do async http requests in it.
	// Therefore, we can't resolve the blob url at (markdown) compile time.
	// To work around this, we modify the url after rendering it in the vue component.
	// We're doing the whole thing in the next tick to ensure the image elements are available in the
	// dom tree. If we're calling this right after setting this.preview it could be the images were
	// not already made available.
	// Some docs at https://stackoverflow.com/q/62865160/10924593
	nextTick().then(async () => {
		const attachmentImage = document.querySelectorAll<HTMLImageElement>('.attachment-image')
		if (attachmentImage) {
			Array.from(attachmentImage).forEach(async (img) => {
				// The url is something like /tasks/<id>/attachments/<id>
				const parts = img.dataset.src?.slice(window.API_URL.length + 1).split('/')
				const taskId = Number(parts[1])
				const attachmentId = Number(parts[3])
				const cacheKey: CacheKey = `${taskId}-${attachmentId}`

				if (typeof loadedAttachments.value[cacheKey] !== 'undefined') {
					img.src = loadedAttachments.value[cacheKey]
					return
				}

				const attachment = new AttachmentModel({taskId: taskId, id: attachmentId})

				const url = await attachmentService.getBlobUrl(attachment)
				img.src = url
				loadedAttachments.value[cacheKey] = url
			})
		}

		const textCheckbox = document.querySelectorAll<HTMLInputElement>(`.text-checkbox-${checkboxId.value}`)
		if (textCheckbox) {
			Array.from(textCheckbox).forEach(check => {
				check.removeEventListener('change', handleCheckboxClick)
				check.addEventListener('change', handleCheckboxClick)
				check.parentElement?.classList.add('has-checkbox')
			})
		}
	})
}

function handleCheckboxClick(e: Event) {
	// Find the original markdown checkbox this is targeting
	const checked = (e.target as HTMLInputElement).checked
	const numMarkdownCheck = Number((e.target as HTMLInputElement).dataset.checkboxNum)

	const index = findNthIndex(text.value, numMarkdownCheck)
	if (index < 0 || typeof index === 'undefined') {
		console.debug('no index found')
		return
	}
	const projectPrefix = text.value.substring(index, index + 1)

	console.debug({index, projectPrefix, checked, text: text.value})

	text.value = replaceAt(text.value, index, `${projectPrefix} ${checked ? '[x]' : '[ ]'} `)
	bubbleNow()
	emit('save', text.value)
	renderPreview()
}

function toggleEdit() {
	isPreviewActive.value = false
	isEditActive.value = true
}

function bubbleSaveClick() {
	isPreviewActive.value = true
	isEditActive.value = false
	renderPreview()
	bubbleNow()
	emit('save', text.value)
}
</script>

<style lang="scss">
@import 'codemirror/lib/codemirror.css';
@import 'highlight.js/scss/base16/equilibrium-gray-light';

.editor {
	.clear {
		clear: both;
	}

	.preview.content {
		margin-bottom: .5rem;
		overflow-wrap: anywhere; // Safari does not understand "break-word" so we put that first to make sure it at least is able to show it somewhat properly there.
		overflow-wrap: break-word;

		ul li {
			input[type="checkbox"] {
				margin-right: .5rem;
			}

			&.has-checkbox {
				margin-left: -1.25rem;
				list-style: none;
			}
		}
	}
}

.CodeMirror {
	padding: .5rem;
	border: 1px solid var(--grey-200) !important;
	background: var(--white);

	&-lines pre {
		margin: 0 !important;
	}

	&-placeholder {
		color: var(--grey-400) !important;
		font-style: italic;
	}

	&-cursor {
		border-color: var(--grey-700);
	}
}

.editor-preview {
	padding: 0;

	&-side {
		padding: .5rem;
	}
}

.editor-toolbar {
	background: var(--grey-50);
	border: 1px solid var(--grey-200);
	border-bottom: none;

	button {
		color: var(--grey-700);

		&.active {
			background: var(--grey-200);
		}

		svg {
			vertical-align: middle;

			&, rect {
				width: 20px;
				height: 20px;
			}
		}

		&::after {
			position: absolute;
			top: 24px;
			margin-left: -3px;
		}

		&:hover {
			background: var(--grey-200);
			border-color: var(--grey-300);
		}
	}

	i.separator {
		border-color: var(--grey-200) !important;
	}
}

pre.CodeMirror-line {
	margin-bottom: 0 !important;
	color: var(--grey-700) !important;
}

.cm-header {
	font-family: $vikunja-font;
	font-weight: 400;
}

ul.actions {
	font-size: .8rem;
	margin: 0;

	li {
		display: inline-block;

		&::after {
			content: '·';
			padding: 0 .25rem;
		}

		&:last-child:after {
			content: '';
		}
	}

	&, a {
		color: var(--grey-500);

		&.done-edit {
			color: var(--primary);
		}
	}

	a:hover {
		text-decoration: underline;
	}
}

.vue-easymde.content {
	margin-bottom: 0 !important;
}
</style>
