/*******************************************************************************
* Copyright (c) 2006 IONA Technologies PLC
* 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:
*     IONA Technologies PLC - initial API and implementation
*******************************************************************************/
package org.eclipse.stp.sc.common.workspace;

import java.util.ArrayList;
import java.util.Arrays;

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


public abstract class AbstractNature implements IProjectNature {
    
    public abstract String getNatureID();
    
    private IProject project;
    
    public void configure() throws CoreException {
    }

    public void deconfigure() throws CoreException {
    }
    
    /** 
	 * Returns the project to which this project nature applies.
	 *
	 * @return the project handle
	 */
	public IProject getProject() {
		return project;
	}

	/**
	 * Sets the project to which this nature applies.
	 * Used when instantiating this project nature runtime.
	 * This is called by <code>IProject.create()</code> or
	 * <code>IProject.setDescription()</code>
	 * and should not be called directly by clients.
	 *
	 * @param project the project to which this nature applies
	 */
	public void setProject(IProject project) {
		this.project = project;
	}

    
	public void addToProject(IProject project) throws CoreException {
        if (!project.hasNature(getNatureID())) {
            IProjectDescription desc = project.getDescription();
            String[] natures = desc.getNatureIds();
            String[] newNatures = new String[natures.length + 1];
            System.arraycopy(natures, 0, newNatures, 1, natures.length);
            newNatures[0] = getNatureID();
            desc.setNatureIds(newNatures);
            project.setDescription(desc, null);
        }
    }


    public void removeFromProject(IProject project) throws CoreException {
        if (project.hasNature(getNatureID())) {
            IProjectDescription desc = project.getDescription();
            String[] natures = desc.getNatureIds();
            ArrayList<String> newNatures = new ArrayList<String>(Arrays.asList(natures));
            newNatures.remove(newNatures.indexOf(getNatureID()));
            desc.setNatureIds(newNatures.toArray(new String[newNatures.size()]));
            project.setDescription(desc, null);
        }
    }
    
    public boolean hasNature(IProject aProject) throws CoreException {
    	return aProject.hasNature(getNatureID());
    }

}