import {useToast} from "primevue/usetoast";
import reloadPage from "@/lib/reload_page.js";

class ToastMessage {
	_ref = null

	obj = {
		severity: "info",
		group: "tc",
		summary: "提示", // TODO 实现多语言
		detail: "",
		life: 3000,
		closable: true,
		onClose: e => {
		}
	}

	constructor(ref, message) {
		this._ref = ref
		this.obj.detail = message
	}

	severity(severity) {
		this.obj.severity = severity
		return this
	}

	success() {
		this.obj.severity = "success"
		return this
	}

	error() {
		this.obj.severity = "error"
		this.obj.life = 0
		return this
	}

	failure() {
		return this.error()
	}

	secondary() {
		this.obj.severity = "secondary"
		return this
	}

	warning() {
		this.obj.severity = "warn"
		this.obj.life = 0
		return this
	}

	warn() {
		return this.warning()
	}

	info() {
		this.obj.severity = "info"
		return this
	}

	contrast() {
		this.obj.severity = "contrast"
		return this
	}

	summary(summary) {
		this.obj.summary = summary
		return this
	}

	detail(detail) {
		this.obj.detail = detail
		return this
	}

	closable(closable) {
		this.obj.closable = closable
		return this
	}

	life(life) {
		this.obj.life = life
		return this
	}

	group(group) {
		this.obj.group = group
		return this
	}

	clear() {
		this._ref.removeAllGroups()
		return this
	}

	onClose(closeCallback) {
		this.obj.onClose = closeCallback
		return this
	}

	/**
	 * refresh current page
	 */
	refresh() {
		this.onClose(() => {
			reloadPage()
		})
		return this
	}

	show() {
		this._ref.add(this.obj)
	}

	removeGroup(groupName) {
		this._ref.removeGroup(groupName)
	}
}

export const useToastService = () => {
	const ref = useToast()

	/**
	 * create new toast
	 *
	 * @param message
	 * @returns {ToastMessage}
	 */
	const newToast = (message) => {
		return new ToastMessage(ref, message)
	}

	return {newToast}
}