/*
 * (c) Copyright Sysdeo SA 2001, 2002.
 * All Rights Reserved.
 */

package com.sysdeo.eclipse.tomcat;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;

/**
 * Utility class for JDT
 * It might exist better way to implements those operations,
 * or they might already exist in JDT
 */
public final class JDTUtil {

	/**
	 * Constructor
	 */
	private JDTUtil() {
		throw new AssertionError();
	}

	/**
	 * Adds a nature to a project
	 * (From BuildPathsBlock class)
	 * @param project IProject
	 * @param natureId String
	 * @throws CoreException CoreException
	 */
	public static void addNatureToProject(final IProject project, final String natureId) throws CoreException {
		// Needed if project is a IJavaProject
		IProject proj = project.getProject();
		IProjectDescription description = proj.getDescription();
		String[] prevNatures = description.getNatureIds();

		int natureIndex = -1;
		for (int i = 0; i < prevNatures.length; i++) {
			if (prevNatures[i].equals(natureId)) {
				natureIndex = i;
				break;
			}
		}

		// Add nature only if it is not already there
		if (natureIndex == -1) {
			String[] newNatures = new String[prevNatures.length + 1];
			System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
			newNatures[prevNatures.length] = natureId;
			description.setNatureIds(newNatures);
			proj.setDescription(description, null);
		}
	}

	/**
	 * Remove a Nature to a Project
	 * @param project IProject
	 * @param natureId String
	 * @throws CoreException CoreException
	 */
	public static void removeNatureToProject(final IProject project, final String natureId) throws CoreException {
		// Needed if project is a IJavaProject
		IProject proj = project.getProject();
		IProjectDescription description = proj.getDescription();
		String[] prevNatures = description.getNatureIds();

		int natureIndex = -1;
		for (int i = 0; i < prevNatures.length; i++) {
			if (prevNatures[i].equals(natureId)) {
				natureIndex = i;
				break;
			}
		}

		// Remove nature only if it exists...
		if (natureIndex != -1) {
			String[] newNatures = new String[prevNatures.length - 1];
			System.arraycopy(prevNatures, 0, newNatures, 0, natureIndex);
			System.arraycopy(prevNatures, natureIndex + 1, newNatures,
							natureIndex, prevNatures.length - (natureIndex + 1));
			description.setNatureIds(newNatures);
			proj.setDescription(description, null);
		}
	}
}
