import {useDialog} from "primevue/usedialog";

class Dialog {
	_ref = null
	_component = null
	_props = {
		modal: true,
		dismissableMask: true,
		blockScroll: true,
		style: {},
		breakpoints: {},
		maximizable: false
	}
	_templates = {}
	_onCloseFunction = null
	_data = {}

	constructor(ref, component) {
		this._ref = ref
		this._component = component
	}

	modal(b) {
		this._props.modal = b
		return this
	}

	header(headerText) {
		this._props.header = headerText
		return this
	}

	footer(footerText) {
		this._props.footer = footerText
		return this
	}

	data(data) {
		this._data = data
		return this
	}

	style(name, value) {
		this._props.style[name] = value
		return this
	}

	breakpoint(screenWidth, dialogWidth) {
		this._props.breakpoints[screenWidth] = dialogWidth
		return this
	}

	template(slotName, component) {
		this._templates[slotName] = component
		return this
	}

	onClose(f) {
		if (typeof f !== "function") {
			console.error("dialog 'onClose' must be a valid function")
			return this
		}

		this._onCloseFunction = f

		return this
	}

	onShow(f) {
		if (typeof f !== "function") {
			console.error("dialog 'onShow' must be a valid function")
			return this
		}
		this._props["onShow"] = f
		return this
	}

	onAfterHide(f) {
		if (typeof f !== "function") {
			console.error("dialog 'onAfterHide' must be a valid function")
			return this
		}
		this._props["onAfterHide"] = f
		return this
	}

	/**
	 *
	 * @returns {{close:Function, key:String, visible:Boolean}}
	 */
	show() {
		return this._ref.open(this._component, {
			props: this._props,
			templates: this._templates,
			onClose: this._onCloseFunction,
			data: this._data
		})
	}
}

export const useDialogService = () => {
	const ref = useDialog()

	// 可以在弹出的 component 中使用 const dialogRef = inject("dialogRef") 来获取当前的对话框对象
	const newDialog = (component) => {
		return new Dialog(ref, component)
	}

	return {newDialog}
}