package com.smartgwt.sample.client.tinymce;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.JavaScriptObject;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.fields.CanvasItem;
import com.smartgwt.client.widgets.form.fields.events.ShowValueEvent;
import com.smartgwt.client.widgets.form.fields.events.ShowValueHandler;

/**
 * Implements TinyMCE editor as a CanvasItem
 */
public class TinyMCECanvasItem extends CanvasItem {

	// A map to lookup canvasItem instances by MCE instance id
	private static Map<String, TinyMCECanvasItem> instanceMap = new HashMap<String, TinyMCECanvasItem>();
	
	private static final String HEIGHT = "200px";
	private static final String WIDTH = "600px";
	private String currentValue = "";
	private TinyMCECanvas editor;
	
	public TinyMCECanvasItem(String name) {
		super(name);
		setupEditor(WIDTH,HEIGHT);
	}
	public TinyMCECanvasItem(JavaScriptObject jso) {
		super(jso);
		setupEditor(WIDTH,HEIGHT);
	}
	public TinyMCECanvasItem(String name, String title) {
		super(name, title);
		setupEditor(WIDTH,HEIGHT);
	}

	public TinyMCECanvasItem() {
		super();
		setupEditor(WIDTH,HEIGHT);
	}
	public static String getCurrentValue(String instanceId) {
		TinyMCECanvasItem item = instanceMap.get(instanceId);
		return item.currentValue;
	}

	public void setCurrentValue(String currentValue) {
		this.currentValue = currentValue;
	}

	public static void updateValue(String instanceId, String value) {
		SC.logDebug("storing value "+value+" for instance "+instanceId);
 		TinyMCECanvasItem instanceItem = instanceMap.get(instanceId);
 		SC.logDebug("instanceItem is "+instanceItem.getName()+" in form "+instanceItem.getForm().getID());
 		instanceItem.setCurrentValue(value==null ? "" : value);
 		instanceItem.storeValue(value);
	}
	
	
	private void setupEditor(String width, String height) {
		
		setShouldSaveValue(true);
		setApplyPromptToCanvas(false);
		setAutoDestroy(true);
		setWidth(width);
		setHeight(height);
		setOverflow(Overflow.VISIBLE);
		
		editor = new TinyMCECanvas(); 

		instanceMap.put(editor.getElementID(), this);
		
        setCanvas(editor);

		addShowValueHandler(new ShowValueHandler() {
			
			@Override
			public void onShowValue(ShowValueEvent event) {
				TinyMCECanvasItem item = (TinyMCECanvasItem) event.getItem();
				SC.logDebug("ShowValueEvent is putting "+event.getDataValue()+" in "+editor.getElementID());
				String dataValue = (String) event.getDataValue();
				item.setCurrentValue(dataValue);
				TinyMCE.updateContent(editor.getElementID(), dataValue);
			}
		});
	}
	
}

