/*
 * Copyright (c) 2006-2008 Maskat Project.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Maskat Project - initial API and implementation
 */
package org.maskat.ui.views.properties.tabbed.command;

import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.maskat.core.MaskatElement;
import org.maskat.ui.editors.layout.commands.SetPropertyCommand;
import org.maskat.ui.views.properties.tabbed.beanwrapper.EventTreeNode;
import org.maskat.ui.views.properties.tabbed.masterdetails.EventPropertiesMasterDetailsBlock;
import org.maskat.ui.views.properties.tabbed.treenodewrapper.ITreeNode;

public class SetEventPropertyCommand extends SetPropertyCommand {
	
	private Class classType;
	
	private TreeViewer treeViewer;
	
	/***
	 * @param classType class of the treeNode corresponding to the detailpage, who should be refreshed
	 * @param bean the MaskatElement bean
	 * @param propertyName 
	 * @param newValue
	 */
	public SetEventPropertyCommand(TreeViewer treeViewer, Class classType, Object bean, String propertyName, Object newValue) {
		super(bean, propertyName, newValue);
		this.treeViewer = treeViewer;
		this.classType = classType;
	}

	public Class getClassType() {
		return classType;
	}
	
	public Object getBean() {
		return bean;
	}
	
	public void redo() {
		try {
			super.redo();
			updateTree();
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();			
		}		
	}
	
	public void undo() {
		try {
			super.undo();
			updateTree();
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
	}
	
	private void updateTree() {
		ITreeNode treeNode = EventPropertiesMasterDetailsBlock.getTreeNode((MaskatElement)bean, classType);
		if (treeNode instanceof EventTreeNode) {
			treeViewer.refresh(treeNode.getParent(), true);
			treeViewer.expandToLevel(2);
			treeNode = EventPropertiesMasterDetailsBlock.getTreeNode((MaskatElement)bean, classType);
			treeViewer.setSelection(new StructuredSelection(treeNode), true);			
		}else if (treeNode != null) {
			treeViewer.update(treeNode, null);
			treeViewer.setSelection(new StructuredSelection(treeNode), true);
		}
	}
}
