package com.smartgwt.sample.client;

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;

public class CKEditorItem extends CanvasItem {
	private CKEditor editorCanvas;

	public CKEditorItem(String name) {
		super(name);
		editorCanvas = new CKEditor(name);
		this.setCanvas(editorCanvas);
		this.setShouldSaveValue(true);
		
		
		addShowValueHandler( new ShowValueHandler() {
			@Override
			public void onShowValue(ShowValueEvent event) {
				System.out.println(" on show value !");
				CKEditorItem.this.storeValue();
			}
		});
		
		System.out.println("CKEditorItem(" + name + ")");
		
		editorCanvas.setCKEditorItem( this );
	}

	public CKEditorItem() {
		this("testItem");
	}

	@Override
	public void setWidth(String width) {
		super.setWidth(width);
		editorCanvas.setWidth(width);
	}

	@Override
	public void setWidth(int width) {
		super.setWidth(width);
		editorCanvas.setWidth(width);
	}

	@Override
	public void setHeight(String height) {
		super.setHeight(height);
		editorCanvas.setHeight(height);
	}

	@Override
	public void setHeight(int height) {
		super.setHeight(height);
		editorCanvas.setHeight(height);
	}

	@Override
	public Object getValue() {
		return getEditorValue(editorCanvas.getID() + "_ta");
	}

	private native String getEditorValue(String id) /*-{
		if ($wnd.CKEDITOR.instances[id]) {
			return $wnd.CKEDITOR.instances[id].getData();
		}

		return null;
	}-*/;
	

    

	@Override
	public void setValue(String value) {
		super.setValue(value);
		if (editorCanvas.isLoaded())
			setEditorValue(editorCanvas.getID() + "_ta", value);
		else
			editorCanvas.setContents(value);
	}

	private native void setEditorValue(String id, String value) /*-{
		if ($wnd.CKEDITOR.instances[id]) {
			$wnd.CKEDITOR.instances[id].setData(value);
		}
	}-*/;

	@Override
	public void storeValue(Object value) {
		setValue(value);
	}

	public void storeValue() {
		setValue( getValue() );
		storeValue( getValue() );
	}
	
	
}