/*******************************************************************************
* Copyright (c) 2007 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 org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.stp.common.logging.LoggingProxy;
import org.eclipse.wst.common.project.facet.core.IFacetedProject;
import org.eclipse.wst.common.project.facet.core.IProjectFacet;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;
import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
import org.eclipse.wst.common.project.facet.core.internal.FacetCorePlugin;

public class FacetUtils {
	
	public static String JAVAWEB_FACET = "jst.web";
    public static String JAVAWEB_FACET_VERSION = "2.4";
    
    public static String JAVA_FACET = "jst.java";
    public static String JAVA_FACET_VERSION = "5.0"; 
    
    static final String FACET_PROJECT_NATURE 
    = FacetCorePlugin.PLUGIN_ID + ".nature";
    

	private static final LoggingProxy LOG = LoggingProxy.getlogger(FacetUtils.class);
	
	public static void addFacet(IProject project, String facet, String version) throws Exception {
		IProjectFacet pf = ProjectFacetsManager.getProjectFacet(facet);
		IProjectFacetVersion fv = pf.getVersion(version);

		IFacetedProject facetedProject = ProjectFacetsManager.create(project);
		if (!facetedProject.hasProjectFacet(pf))  {
			LOG.debug("install facet:" + facet);
		    facetedProject.installProjectFacet(fv, null, null);
		}
	}
	
	public static void addFacetNature(IProject project) {
		IProjectDescription projDesc;
		try {
			if (project.hasNature(FACET_PROJECT_NATURE)) {
				return;
			}
			projDesc = project.getDescription();
			String[] natures = projDesc.getNatureIds();
			String[] newNatures = new String[natures.length + 1];
			System.arraycopy(natures, 0, newNatures, 0, natures.length);

			newNatures[newNatures.length - 1] = FACET_PROJECT_NATURE;
			projDesc.setNatureIds(newNatures);
			project.setDescription(projDesc, null);
		} catch (CoreException e) {
			LOG.error("error when try to add facet", e);
		}
		
	}
}
