// Copyright (c) 2015, Xhive Global Ltd. and Contributors
// MIT License. See license.txt

xhiveframework.provide("xhiveframework.help");

xhiveframework.help.youtube_id = {};

xhiveframework.help.has_help = function (doctype) {
	return xhiveframework.help.youtube_id[doctype];
};

xhiveframework.help.show = function (doctype) {
	if (xhiveframework.help.youtube_id[doctype]) {
		xhiveframework.help.show_video(xhiveframework.help.youtube_id[doctype]);
	}
};

xhiveframework.help.show_video = function (youtube_id, title) {
	if (xhiveframework.utils.is_url(youtube_id)) {
		const expression =
			'(?:youtube.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu.be/)([^"&?\\s]{11})';
		youtube_id = youtube_id.match(expression)[1];
	}

	// (xhiveframework.help_feedback_link || "")
	let dialog = new xhiveframework.ui.Dialog({
		title: title || __("Help"),
		size: "large",
	});

	let video = $(
		`<div class="video-player" data-plyr-provider="youtube" data-plyr-embed-id="${youtube_id}"></div>`
	);
	video.appendTo(dialog.body);

	dialog.show();
	dialog.$wrapper.addClass("video-modal");

	let plyr;
	xhiveframework.utils.load_video_player().then(() => {
		plyr = new xhiveframework.Plyr(video[0], {
			hideControls: true,
			resetOnEnd: true,
		});
	});

	dialog.onhide = () => {
		plyr?.destroy();
	};
};

$("body").on("click", "a.help-link", function () {
	var doctype = $(this).attr("data-doctype");
	doctype && xhiveframework.help.show(doctype);
});
