/**
 * @author Ove Andersen
 * @version 2.0 July 2015
 */

/*global tinymce:true */

tinymce.PluginManager.add('syntaxhighlighter', function(editor, url) {
	function showDialog() {
		// Get content
		var el = editor.selection.getNode();
		el = editor.dom.getParent(el, "CODE");

		// Get content language
		var lang = "";
		if (el) {
			el.classList.forEach(function(element, index, array) {
				if (element.indexOf("language-") === 0) {
					lang = element.substring(9);
				}
			});
		}

		// Get available languages
		var languages = hljs.listLanguages();
		languages.unshift("nohighlight");

		// Load services
		var injector = angular.element(document.getElementById("umbracoMainPageBody")).injector();
		var dialogService = injector.get("dialogService");

		// Render dialog
		var text = el ? el.innerText : "";
		var dialog = dialogService.open({
			template: url + '/dialog.htm',
			modalClass: 'umb-modal tinymce-syntaxhighlighter-wrapper',
			show: true,
			dialogData: {
				content: text,
				language: lang,
				languages: languages
			},
			callback: function(data) {
				var el = editor.selection.getNode();
				var pre = editor.dom.getParent(el, "PRE");

				editor.undoManager.beforeChange();

				// Remove old node
				if (pre) {
					i = editor.selection.getBookmark();
					pre.innerHTML = "";
					editor.dom.remove(pre, 1);
					editor.selection.moveToBookmark(i);
				}

				var block = editor.dom.create("pre");
				block.innerHTML = "<code class='" + (data.language ? data.language : "")  + "'>" + editor.dom.encode(data.content) + "</code>";
				editor.selection.setNode(block);

				editor.undoManager.add();
			}
		});
	};

	// Add custom css and js
	editor.on('init', function() {
	    var shCssUrl = url + '/styles/syntaxhighlighter.css';
		var hlCssUrl = "//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.6/styles/default.min.css";
		var hlJsUrl = "//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.6/highlight.min.js";

        shCssLink = editor.dom.create('link', { rel: 'stylesheet', href: shCssUrl });
		hlCssLink = editor.dom.create('link', { rel: 'stylesheet', href: hlCssUrl });
		hlJsLink = editor.dom.create('script', { src: hlJsUrl });
        document.getElementsByTagName('head')[0].appendChild(shCssLink);
		document.getElementsByTagName('head')[0].appendChild(hlCssLink);
		document.getElementsByTagName('head')[0].appendChild(hlJsLink);
    });

	// Add button to toolbar
	editor.addButton('syntaxhighlighter', {
		classes: 'widget btn syntaxhighlighter-button',
		image: url + '/images/syntaxhighlighter.svg',
		tooltip: 'Insert/Edit Source Code',
		onclick: showDialog,
		stateSelector: 'pre code'
	});
});
