/*******************************************************************************
 * Copyright (c) 2012 Joseph Carroll
 * 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:
 *     Joseph Carroll <jdsalingerjr@gmail.com> - initial API and implementation
 *******************************************************************************/
package braintrader.application;

import java.lang.reflect.Method;

import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.application.IWorkbenchConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;

import braintrader.core.contexts.TraderContextFactory;

public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {

	private static final String PERSPECTIVE_ID = "braintrader.blockdiagram.ui.perspective.diagrameditor";

	@Override
	public void initialize(IWorkbenchConfigurer configurer) {
		IWorkbench workbench = configurer.getWorkbench();
		try {
			// Would be better to use a lifecycle hook like an addon
			Class<?> clazz = workbench.getClass();
			Method getContext = clazz.getDeclaredMethod("getContext", (Class<?>[]) null);
			getContext.setAccessible(true);
			Object obj = getContext.invoke(workbench, (Object[]) null);
			if (!(obj instanceof IEclipseContext)) {
				throw new IllegalStateException("No Application Context");
			}
			// Store the context
			Method setContext = TraderContextFactory.class.getDeclaredMethod("setWorkbenchContext", Object.class);
			setContext.setAccessible(true);
			setContext.invoke(TraderContextFactory.class, obj);
		} catch (SecurityException | ReflectiveOperationException e) {
			// Log
			e.printStackTrace();
		}
	}
	
	
	public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
		return new ApplicationWorkbenchWindowAdvisor(configurer);
	}

	public String getInitialWindowPerspectiveId() {
		return PERSPECTIVE_ID;
	}

}
