/*! Kaleidoscope kaleidoscope.js
 * https://kaleidoscope.app  */

let ksdiffURL = safari.extension.baseURI + 'ksdiff.js';
let ksdiffScriptLoaded = (document && document.querySelector('script[src="'+ksdiffURL+'"]'))

if (!ksdiffScriptLoaded) {
  document.addEventListener('ksdiffEvent', function(event) {
	safari.extension.dispatchMessage('ksdiff', event.detail);
  });

  safari.self.addEventListener('message', function(event) {
	var text = '';
	switch (event.name) {
	  case 'diff-page':
		text = document.documentElement.outerHTML;
		break;
		
	  case 'diff-element':
		text = window.getSelection().anchorNode.parentNode.outerHTML;
		break;
		
	  case 'diff-style':
		text = styleText(window.getSelection().anchorNode.parentNode);
		break;
	}
	let userInfo = {'text': text};
	safari.extension.dispatchMessage('ksdiff', userInfo);
  });
}

function styleText(element) {
  return JSON.stringify(getAllStyles(element), null, 2);
}

function getAllStyles(elem) {
	if (!elem) return []; // Element does not exist, empty list.
	var win = document.defaultView || window, style, styleNode = [];
	if (win.getComputedStyle) { /* Modern browsers */
		style = win.getComputedStyle(elem, '');
		for (var i=0; i<style.length; i++) {
			styleNode.push( style[i] + ':' + style.getPropertyValue(style[i]) );
			//			   ^name ^		   ^ value ^
		}
	} else if (elem.currentStyle) { /* IE */
		style = elem.currentStyle;
		for (var name in style) {
			styleNode.push( name + ':' + style[name] );
		}
	} else { /* Ancient browser..*/
		style = elem.style;
		for (var i=0; i<style.length; i++) {
			styleNode.push( style[i] + ':' + style[style[i]] );
		}
	}
	return styleNode;
}

// inject a script from the extension's files
// into the execution environment of the main page
document.addEventListener('DOMContentLoaded', function(event) {
	let script = document.createElement('script');
	script.src = ksdiffURL;
	if (!document.querySelector('script[src="'+ksdiffURL+'"]')) {
		document.documentElement.appendChild(script);
	}
});
