package jp.co.cybec.laxide.editParts;

import java.beans.PropertyChangeEvent;

import jp.co.cybec.laxide.LetsAjaxEditor;
import jp.co.cybec.laxide.editpolicies.LetsAjaxComponentEditPolicy;
import jp.co.cybec.laxide.editpolicies.LetsAjaxDirectEditPolicy;
import jp.co.cybec.laxide.model.base.LetsAjaxImageModel;

import org.eclipse.draw2d.CompoundBorder;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.LineBorder;
import org.eclipse.draw2d.MarginBorder;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.graphics.Image;

/**
 * イメージを描画するクラス ファイル名：LetsAjaxImageEditPart.java
 * 
 * @author nakamura 作成時刻：13:33:02
 * 
 */
public class LetsAjaxImageEditPart extends EditPartWithListener {

	private LetsAjaxDirectEditManager directManager = null;

	/**
	 * 属性が変更された時に呼ばれるメソッド
	 * 
	 * @see jp.co.cybec.laxide.editParts.EditPartWithListener#propertyChange(java.beans.PropertyChangeEvent)
	 */
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals(LetsAjaxImageModel.P_CONSTRAINT)) {
			LetsAjaxImageModel model = (LetsAjaxImageModel) getModel();
			Label label = (Label) getFigure();
			label.setSize(model.getConstraint().width, model.getConstraint().height);
			
			model.setComponentWidth(Integer.toString(model.getConstraint().width));
			model.setComponentHeight(Integer.toString(model.getConstraint().height));
			
			refreshVisuals();
		}
	}
	
	/**
	 * イメージの生成
	 * 
	 * @see org.eclipse.gef.editparts.AbstractGraphicalEditPart#createFigure()
	 */
	protected IFigure createFigure() {
		Image img = new Image(null, LetsAjaxEditor.class
				.getResourceAsStream("image.gif"));
		
		Label label = new Label();
		label.setBorder(new CompoundBorder(new LineBorder(),
				new MarginBorder(3)));
		label.setOpaque(true);
		label.setIcon(img);
		label.setSize(60, 50); 
		
		return label;
	}

	protected void createEditPolicies() {
		installEditPolicy(EditPolicy.COMPONENT_ROLE,
				new LetsAjaxComponentEditPolicy());
		installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE,
				new LetsAjaxDirectEditPolicy());
	}

	protected void refreshVisuals() {
		Rectangle constraint = ((LetsAjaxImageModel) getModel())
				.getConstraint();

		((GraphicalEditPart) getParent()).setLayoutConstraint(this,
				getFigure(), constraint);
	}

	public void performRequest(Request req) {
		if (req.getType().equals(RequestConstants.REQ_DIRECT_EDIT)) {
			performDirectEdit();
			return;
		}
		super.performRequest(req);
	}

	private void performDirectEdit() {
		if (directManager == null) {
			directManager = new LetsAjaxDirectEditManager(this,
					TextCellEditor.class, new LetsAjaxCellEditorLocator(
							getFigure()));
		}
		directManager.show();
	}

}
