// Copyright (c) 2015, InfluxFramework LLC
// MIT License. See license.txt

influxframework.provide("influxframework.help");

influxframework.help.youtube_id = {};

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

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

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

	// (influxframework.help_feedback_link || "")
	let dialog = new influxframework.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;
	influxframework.utils.load_video_player().then(() => {
		plyr = new influxframework.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 && influxframework.help.show(doctype);
});
