package jp.hasc.hasctool.ui.bdeditor2;

import java.util.HashSet;
import java.util.List;

import jp.hasc.hasctool.core.blockdiagram.model.BeanBlock;
import jp.hasc.hasctool.core.blockdiagram.model.BlockDiagram;
import jp.hasc.hasctool.core.blockdiagram.model.Connection;
import jp.hasc.hasctool.core.blockdiagram.model.Shape;
import jp.hasc.hasctool.ui.bdeditor2.parts.BlockEditPart;
import jp.hasc.hasctool.ui.bdeditor2.parts.ConnectionEditPart;
import jp.hasc.hasctool.ui.bdeditor2.parts.DiagramEditPart;
import jp.hasc.hasctool.ui.bdeditor2.parts.ShapeEditPart;

import org.eclipse.gef.ui.actions.Clipboard;
import org.eclipse.gef.ui.actions.SelectionAction;
import org.eclipse.ui.actions.ActionFactory;

/**
 * @author iwasaki
 */
public class BlockDiagramEditorCopyAction extends SelectionAction{
	/** logger for this class */
	private final static org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory
			.getLog(BlockDiagramEditorCopyAction.class);
	
	private BlockDiagramEditor editor_;
	
	public BlockDiagramEditorCopyAction(BlockDiagramEditor part) {
		super(part);
		editor_=part;
	}

	@Override
	protected boolean calculateEnabled() {
		return true;
	}
	
	@Override
	protected void init() {
		setId(ActionFactory.COPY.getId());
		setText("Copy");
	}
	
	@Override
	public void run() {
		List<?> objs = getSelectedObjects();
		//LOG.debug(objs);
		if (objs==null || objs.size()==0) return;
		if (objs.size()==1 && objs.get(0) instanceof DiagramEditPart) return;
		
		BlockDiagram srcbd=editor_.getModel().getBlockDiagram();
		BlockDiagram destbd=new BlockDiagram();
		
		// add blocks and comments
		HashSet<String> destBlockNames = new HashSet<String>();
		for(Object o : objs) {
			if (o instanceof BlockEditPart) {
				BeanBlock blk = ((BlockEditPart)o).getCastedModel().getBeanBlock();
				destbd.addBlock(blk);
				destBlockNames.add(blk.getName());
			}else if (o instanceof ShapeEditPart) {
				Shape s = ((ShapeEditPart)o).getCastedModel().getShape();
				destbd.addShape(s);
			}else if (o instanceof ConnectionEditPart) {
				// ignore
			}else{
				LOG.warn("Unknown object: " + o);
			}
		}
		
		// add connections
		for(Connection c : srcbd.getConnections()) {
			if (destBlockNames.contains(c.getInputPortReference().getBlockName()) &&
				destBlockNames.contains(c.getOutputPortReference().getBlockName())
			) {
				destbd.addConnection(c);
			}
		}
		
		// copy
		//LOG.debug(BlockDiagramEditor.newXStream()(destbd));
		Clipboard.getDefault().setContents(BlockDiagramEditor.cloneByXStream(destbd));
		LOG.debug("copied");
	}
}
