/**
 * File:    TestIntegrationInPlatform.java
 * Created: 14.01.2009
 *
 *
/*******************************************************************************
 * Copyright (c) 2009    Open Wide (www.openwide.fr)
 *
 * 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:
 *    Mickael Istria, Open Wide, Lyon, France
 *      - Creation and Implementation
 *******************************************************************************/
package org.eclipse.jwt.tests.integration;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.net.URL;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jwt.we.editors.WEEditor;
import org.eclipse.jwt.we.misc.util.GeneralHelper;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.internal.ErrorEditorPart;

public class TestIntegrationInPlatform extends TestCase
{

	/**
	 * Returns the JUnit test suite that implements the
	 * <b>TestIntegrationInPlatform</b> definition.
	 */
	public static Test suite()
	{
		TestSuite testVersion = new TestSuite(TestIntegrationInPlatform.class);
		return testVersion;
	}


	@SuppressWarnings("restriction")
	public void testOpenEditor() throws Exception
	{
		GeneralHelper.setJUnitMode(true);

		System.out.println("testOpenEditor");
		System.out.println("init resource");
		URL resource = getClass().getResource("ExternalApplications.workflow");
		System.out.println("url:" + resource.toString());
		URI resourceUri = new URI(FileLocator.toFileURL(resource).toExternalForm()
				.replaceAll(" ", "%20"));
		System.out.println("uri:" + resourceUri.toString());
		System.out.println("get expected version");
		String expectedVersion = "fileversion=\"" + GeneralHelper.getWEVersion() + "\"";
		assertTrue("Test workflow is not of the same version as JWT WE, can't run test",
				fileToString(resourceUri).contains(expectedVersion));

		System.out.println("get workbench page");
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
				.getActivePage();

		System.out.println("open editor");
		IEditorPart editor = IDE.openEditor(page, resourceUri,
				"org.eclipse.jwt.we.editors.WEEditor", true);
		assertFalse("An error occured while opening JWT Editor",
				editor instanceof ErrorEditorPart);
		assertTrue("Workflow model is not opened with JWT Editor",
				editor instanceof WEEditor);
		System.out.println("open editor finished");
		GeneralHelper.setJUnitMode(false);
	}


	public String fileToString(URI uri) throws Exception
	{
		File file = new File(uri);
		int byteReadNb = 0;
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
		byte[] buf = new byte[512];
		StringBuffer readSbuf = new StringBuffer();
		while ((byteReadNb = bis.read(buf, 0, 512)) != -1)
		{
			readSbuf.append(new String(buf, 0, byteReadNb)); // TODO or put
			// encoding here
		}
		return readSbuf.toString();
	}


	public void testCategoriesNewWizard()
	{
		System.out.println("testCategoriesNewWizard");
		int n = countJWTCategories("org.eclipse.ui.newWizards");
		assertEquals("Expected 1 JWT related category for New wizards, got " + n, 1, n);
	}


	public void testCategoriesExampleWizard()
	{
		System.out.println("testCategoriesExampleWizard");
		int n = countJWTExampleCategories("org.eclipse.ui.newWizards");
		assertEquals("Expected 1 JWT example category for Example wizards, got " + n, 1,
				n);
	}


	public void testCategoriesImportWizards()
	{
		System.out.println("testCategoriesImportWizards");
		int n = countJWTCategories("org.eclipse.ui.importWizards");
		assertEquals("Expected 1 JWT related category for Import wizards, got " + n, 1, n);
	}


	public void testCategoriesExportWizards()
	{
		System.out.println("testCategoriesExportWizards");
		int n = countJWTCategories("org.eclipse.ui.exportWizards");
		assertEquals("Expected 1 JWT related category for Export wizards, got " + n, 1, n);
	}


	private int countJWTExampleCategories(String extensionPointId)
	{
		IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(
				extensionPointId);
		IConfigurationElement[] configurationElements = extension
				.getConfigurationElements();
		int res = 0;
		for (int i = 0; i < configurationElements.length; i++)
		{
			IConfigurationElement configElement = configurationElements[i];
			if (configElement.getName().equals("category"))
			{
				String name = configElement.getAttribute("name");
				String parentCategory = configElement.getAttribute("parentCategory");
				if (parentCategory == null)
					parentCategory = "";
				if ((name.toLowerCase().contains("java workflow tool") || name
						.toLowerCase().contains("jwt"))
						&& parentCategory.equals("org.eclipse.ui.Examples"))
				{
					res++;
				}
			}
		}
		return res;
	}


	private int countJWTCategories(String extensionPointId)
	{
		IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(
				extensionPointId);
		IConfigurationElement[] configurationElements = extension
				.getConfigurationElements();
		int res = 0;
		for (int i = 0; i < configurationElements.length; i++)
		{
			IConfigurationElement configElement = configurationElements[i];
			if (configElement.getName().equals("category"))
			{
				String name = configElement.getAttribute("name");
				String parentCategory = configElement.getAttribute("parentCategory");
				if (parentCategory == null)
					parentCategory = "";
				if ((name.toLowerCase().contains("java workflow tool") || name
						.toLowerCase().contains("jwt"))
						&& !parentCategory.equals("org.eclipse.ui.Examples"))
				{
					res++;
				}
			}
		}
		return res;
	}

}
