package eu.ydp.empiria.player.client.controller.extensions.jswrappers;

import java.util.Map;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.XMLParser;

import eu.ydp.empiria.player.client.controller.extensions.ExtensionType;
import eu.ydp.empiria.player.client.controller.extensions.types.StyleSocketUserExtension;
import eu.ydp.empiria.player.client.style.StyleSocket;
import eu.ydp.empiria.player.client.util.js.JSArrayUtils;

public class JsStyleSocketUserExtension extends JsExtension implements StyleSocketUserExtension {

	protected JavaScriptObject styleSocketJs;
	protected StyleSocket styleSocket;
	
	public JsStyleSocketUserExtension(){
		super();
	}
	
	@Override
	public ExtensionType getType() {
		return ExtensionType.EXTENSION_SOCKET_USER_STYLE_CLIENT;
	}

	@Override
	public void init() {
		styleSocketJs = createStyleSocketJs();
		setStyleSocketJs(extensionJsObject, styleSocketJs);
	}
	
	public void setStyleSocket(StyleSocket ss){
		styleSocket = ss;
	}
	
	private native JavaScriptObject createStyleSocketJs()/*-{
		var instance = this;
		var socket = [];
		socket.getStyle = function(element){
			return instance.@eu.ydp.empiria.player.client.controller.extensions.jswrappers.JsStyleSocketUserExtension::getStyle(Lcom/google/gwt/dom/client/Element;)(element);
		}
		return socket;
	}-*/;
	
	private native void setStyleSocketJs(JavaScriptObject extension, JavaScriptObject socket)/*-{
		if (typeof extension.setStyleSocket == 'function'){
			extension.setStyleSocket(socket);
		}
	}-*/;
	
	private JavaScriptObject getStyle(com.google.gwt.dom.client.Element element){
		Document xmlDocument = XMLParser.parse(element.getString());
		Map<String, String> styles = styleSocket.getStyles(xmlDocument.getDocumentElement());
		JavaScriptObject stylesJsArray = JavaScriptObject.createObject();
		
		for (String currKey : styles.keySet()){
			JSArrayUtils.fillArray(stylesJsArray, currKey, styles.get(currKey));
		}
		
		return stylesJsArray;
	} 

}

@@ -185,24 +185,67 @@
 .Document;%0D%0A
+import com.google.gwt.xml.client.Element;%0D%0A
 import com.g
@@ -1766,20 +1766,19 @@
 %0D%0A%09%09
-Docu
+Ele
 ment xml
 Docu
@@ -1773,20 +1773,19 @@
 ment xml
-Docu
+Ele
 ment = X
@@ -1797,31 +1797,72 @@
 ser.
-parse(element.getString
+createDocument().createElement(element.getNodeName().toLowerCase
 ());
@@ -1923,37 +1923,15 @@
 (xml
-Document.getDocument
 Element
-()
 );%0D%0A

upgrade node from DOM to XML translation; task#56152