package com.smartgwt.sample.client.tinymce;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.user.client.Timer;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.HTMLFlow;

/**
 * A SmartGWT Canvas containing a TinyMCE editor.
 */
public class TinyMCECanvas extends Canvas {
	
	private String elementID;
	private String cssWidth = "700px";
	private String cssHeight = "200px";

	/**
	 * Create an HTML editor widget using Tiny MCE.
	 */
	public TinyMCECanvas() {
		TinyMCE.initMCE();
		setElementID(SC.generateID());
	}
	@Override
	public void destroy() {
		SC.logDebug("unloading "+getElementID());
		TinyMCE.unload(getElementID());
		super.destroy();
	};
	/**
	 * Initialize the Canvas's instance of the editor
	 * The Time is needed to make sure the div is already in the DOM
	 * so it can be replaced with the editor widget.
	 */
	public void initCanvas() {
		setWidth(cssWidth);
		setHeight(cssHeight);
		final HTMLFlow textArea = new HTMLFlow();
		textArea.hide();
		textArea.setWidth(cssWidth);
		textArea.setHeight(cssHeight);
		addChild(textArea);
		textArea.setContents("<div id=\""+getElementID()+"\"></div>");
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
			
			@Override
			public void execute() {
				SC.logDebug("Initializing element "+getElementID());
				TinyMCE.initInstance(getElementID());
				textArea.show();
			}
		});
	}

	/**
	 * @return The DOM element ID assigned to the TinyMCE editor instance.
	 */
	public String getElementID() {
		return elementID;
	}

	private void setElementID(String elementID) {
		this.elementID = elementID;
	}
}
