package org.eclipse.e4.ui.splash.internal.aspects;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.eclipse.core.runtime.IProduct;
import org.eclipse.core.runtime.Platform;
import org.eclipse.e4.workbench.ui.internal.Workbench;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.ui.internal.misc.StatusUtil;
import org.eclipse.ui.internal.splash.EclipseSplashHandler;
import org.eclipse.ui.internal.splash.SplashHandlerFactory;
import org.eclipse.ui.splash.AbstractSplashHandler;
import org.eclipse.ui.statushandlers.StatusManager;

@Aspect
public class SplashHandlerAsp {
	@Pointcut("execution(* createGUI(..)) && this( w )")
	public void createGUIExecution(Workbench w) {
	}

	@After("createGUIExecution( w )")
	public void a1(Workbench w) {
		Shell wShell = w.getShell();
		try {
			Shell splash = WorkbenchPlugin.getSplashShell(wShell.getDisplay());
			String splashLoc = System
					.getProperty("org.eclipse.equinox.launcher.splash.location"); //$NON-NLS-1$
			final Image bg = loadImage(wShell.getDisplay(), splashLoc);
			splash.setBackgroundImage(bg);

			AbstractSplashHandler ih = getSplashHandler();
			ih.init(splash);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Image loadImage(Display display, String splashLoc) {
		Image background = null;

		if (splashLoc != null) {
			try {
				InputStream input = new BufferedInputStream(
						new FileInputStream(splashLoc));
				background = new Image(display, input);
			} catch (IOException e) {
				StatusManager.getManager().handle(
						StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, e));
			}
		}

		return background;
	}

	private static AbstractSplashHandler getSplashHandler() {
		AbstractSplashHandler splash = null;

		IProduct product = Platform.getProduct();

		if (product != null) {
			splash = SplashHandlerFactory.findSplashHandlerFor(product);
		}

		if (splash == null) {
			splash = new EclipseSplashHandler();
		}

		return splash;
	}
}
