/**
 * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

import { createApp } from 'vue'
import NcReferencePickerModal from './../../components/NcRichText/NcReferencePicker/NcReferencePickerModal.vue'
import { getProvider } from './providerHelper.js'

/**
 * Creates a reference picker modal and return a promise which provides the link URL
 *
 * @param providerId - Optional ID of initial selected provider
 * @param isInsideViewer - Should be true if this function is called while the Viewer is displayed
 */
export async function getLinkWithPicker(providerId?: string, isInsideViewer?: boolean): Promise<string> {
	const modalId = 'referencePickerModal'
	const modalElement = document.createElement('div')
	modalElement.id = modalId
	document.body.append(modalElement)

	const { promise, reject, resolve } = Promise.withResolvers<string>()
	const initialProvider = (providerId && getProvider(providerId)) || null
	const view = createApp(NcReferencePickerModal, {
		initialProvider,
		isInsideViewer,
		onCancel() {
			view.unmount()
			reject(new Error('User cancellation'))
		},
		onSubmit(link: string) {
			view.unmount()
			resolve(link)
		},
	})
	view.mount(modalElement)

	return promise
}

/**
 * Creates a reference picker modal and return a promise which provides the reference object.
 *
 * The function guarantees a `link: string` on the resolved object. Custom picker elements may
 * include additional fields (e.g. `title`).
 *
 * @experimental The shape of the resolved reference and the signature of this function may still change.
 *
 * @template T - Expected shape of the resolved reference, must include `link: string`
 * @param providerId - Optional ID of initial selected provider
 * @param isInsideViewer - Should be true if this function is called while the Viewer is displayed
 */
export async function getReferenceWithPicker<T extends { link: string }>(providerId?: string, isInsideViewer?: boolean): Promise<T> {
	const modalId = 'referencePickerModal'
	const modalElement = document.createElement('div')
	modalElement.id = modalId
	document.body.append(modalElement)

	const { promise, reject, resolve } = Promise.withResolvers<T>()
	const initialProvider = (providerId && getProvider(providerId)) || null
	const view = createApp(NcReferencePickerModal, {
		initialProvider,
		isInsideViewer,
		onCancel() {
			view.unmount()
			reject(new Error('User cancellation'))
		},
		onPick(reference: T) {
			view.unmount()
			resolve(reference)
		},
	})
	view.mount(modalElement)

	return promise
}
