(function () {
	CKEDITOR.plugins.add("drawio", {
		requires: "button",
		init: function (editor) {
			CKEDITOR.skin.addIcon("drawio", this.path + "icon/drawlogo.png");

			editor.addCommand("drawio", {
				context: "draw.io",
				exec: function (_, diagram) {
					var iframe = document.createElement("iframe");
					iframe.setAttribute(
						"src",
						"/reference/drawio-wiki/?embed=1&spin=1&modified=unsavedChanges&proto=json&lang=ko"
					);
					iframe.setAttribute("width", "100%");
					iframe.setAttribute("height", "100%");
					iframe.setAttribute("title", "draw.io");
					iframe.setAttribute("frameBorder", "0");
					iframe.style.position = "fixed";
					iframe.style.top = 0;
					iframe.style.left = 0;
					iframe.style.zIndex = 99999;

					var handleDrawio = function (event) {
						if (event.data.length > 0) {
							var data = JSON.parse(event.data);
							console.log(data);
							var msg = data.event;

							switch (msg) {
								case "init":
									iframe.contentWindow.postMessage(
										JSON.stringify({
											action: "load",
											autosave: 0,
											xmlpng: diagram.src
										}),
										"*"
									);
									break;

								case "save":
									iframe.contentWindow.postMessage(
										JSON.stringify({
											spinKey: "saving",
											action: "export",
											format: "xmlpng"
										}),
										"*"
									);
									break;

								case "export":
									editor.fire("saveDiagram", {
										img: data.data,
										xml: data.xml
									});

									break;

								case "exit":
									window.removeEventListener("message", handleDrawio);
									document.body.removeChild(iframe);
									break;

								default:
							}
						}
					};

					window.addEventListener("message", handleDrawio);
					document.body.appendChild(iframe);
				}
			});

			editor.ui.addButton("drawio", {
				label: "draw.io",
				command: "drawio",
				toolbar: "basicstyles,1"
			});

			if (editor.addMenuItem) {
				editor.addMenuGroup("drawio");
				editor.addMenuItem("drawio", {
					label: "draw.io",
					group: "drawio",
					icon: "drawio"
				});

				editor.getMenuItem("drawio").onClick = function () {
					var element = editor.getSelection().getStartElement();
					editor.fire("editDiagram", element.$.getAttribute("src"));
				};
			}

			if (editor.contextMenu) {
				editor.contextMenu.addListener(function (element) {
					if (element.getName() === "img" && element.$.getAttribute("alt") === "draw.io Diagram") {
						return {
							drawio: CKEDITOR.TRISTATE_OFF
						};
					}
				});
			}
		}
	});

	CKEDITOR.DRAWIO = "drawio";
})();
