package jp.co.cybec.laxide.editParts;

import java.beans.PropertyChangeEvent;

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

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;

/**
 * コンボボックスを生成するクラス ファイル名：LetsAjaxComboBoxEditPart.java
 * 
 * @author nakamura 作成時刻：13:21:40
 * 
 */
public class LetsAjaxComboBoxEditPart 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(LetsAjaxComboBoxModel.P_CONSTRAINT)) {
			LetsAjaxComboBoxModel model = (LetsAjaxComboBoxModel) getModel();
			Label label = (Label) getFigure();
			model.setComponentWidth(Integer.toString(label.getSize().width));
			model.setComponentHeight(Integer.toString(label.getSize().height));

			refreshVisuals();
		} else if (evt.getPropertyName().equals(
				LetsAjaxComboBoxModel.P_DEFAULTVALUE)) {
			Label label = (Label) getFigure();
			label.setText((String) evt.getNewValue());
		}
	}

	/**
	 * コンボボックスを生成する
	 * 
	 * @see org.eclipse.gef.editparts.AbstractGraphicalEditPart#createFigure()
	 */
	protected IFigure createFigure() {
		LetsAjaxComboBoxModel model = (LetsAjaxComboBoxModel) getModel();

		Label label = new Label();
		label.setBorder(new CompoundBorder(new LineBorder(),
				new MarginBorder(3)));
		label.setOpaque(true);
		label.setText(model.getDefaultValue());
		label.setSize(60, 20);

		return label;
	}

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

	protected void refreshVisuals() {
		Rectangle constraint = ((LetsAjaxComboBoxModel) 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();
	}
}
