/**
 * File:    EMFResourceUtils.java
 * Created: 20.07.2008
 *
 *
/*******************************************************************************
 * Copyright (c) 2008-2009 Open Wide SA <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:
 *    Marc Dutoo, Open Wide SA 
 *    	- initial API and implementation
 *******************************************************************************/

package org.eclipse.jwt.we.conf.model.resource.internal;

import java.util.ArrayList;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.jwt.we.conf.model.plugin.ConfPlugin;
import org.eclipse.jwt.we.conf.model.plugin.internal.EMFUtils;


/**
 * Resource-minded EMF utils
 * 
 * @version $Id: EMFResourceUtils.java,v 1.1 2010-05-10 08:27:22 chsaad Exp $
 * @author Marc Dutoo, Open Wide SA
 */
public class EMFResourceUtils {


	/**
	 * Cleans the given badly loaded resource from the resourceSet
	 * @param resourceSet
	 * @param badlyLoadedResourceUri badly loaded resource
	 */
	public static final void cleanBadlyLoadedResource(ResourceSet resourceSet, URI badlyLoadedResourceUri) {
		Resource badlyLoadedResource = resourceSet.getResource(badlyLoadedResourceUri, false);
		if (badlyLoadedResource != null) {
			if (badlyLoadedResource.isLoaded()) {
				badlyLoadedResource.unload();
			}
			resourceSet.getResources().remove(badlyLoadedResource);
		}
	}
	

	/**
	 * Helper that updates then unloads all 
	 * TODO move
	 * @param modelRoot (ConfModel)
	 * @param oldURI
	 * @param newURI
	 * @return reloaded, updated model
	 */
	public static final void updateModelExternalResourceUri(EObject modelRoot, URI oldURI, URI newURI) {
		Resource modelResource = modelRoot.eResource();
		URI ownURI = modelResource.getURI();
		
		for (TreeIterator<EObject> eObjectIt = modelRoot.eAllContents(); eObjectIt.hasNext();) {
			EObject eObject = eObjectIt.next();

			// getting enrichedModel URI and checking it
			URI eObjectResourceURI = EMFUtils.getResourceOrProxyURI(eObject);
			
			if (ownURI.equals(eObjectResourceURI)) {
				// update cross references of model element
				updateModelElementCrossReferenceExternalResourceUri(eObject, oldURI, newURI);
				
			} else if (oldURI.equals(eObjectResourceURI)) {
				// update proxy containment reference TODO useful ?
				EMFUtils.updateResourceOrProxyURI(eObject, newURI);
			}
		}
		
		// update cross references of model
		updateModelElementCrossReferenceExternalResourceUri(modelRoot, oldURI, newURI);
	}


	/**
	 * Helper
	 * TODO move
	 * @param eObject
	 * @param oldURI
	 * @param newURI
	 */
	private static final void updateModelElementCrossReferenceExternalResourceUri(EObject eObject, URI oldURI, URI newURI) {
		// update cross references of model
		for (EObject refEObject : eObject.eCrossReferences()) {
			URI refEObjectResourceURI = EMFUtils.getResourceOrProxyURI(refEObject);
			if (oldURI.equals(refEObjectResourceURI)) {
				
				// update URI
				EMFUtils.updateResourceOrProxyURI(refEObject, newURI);
			}

		}
	}


	public static void removeResourceFromResourceSet(URI toBeRemovedUri, ResourceSet resourceSet) {
		// unloading all resources at toBeRemovedUri
		for (Resource resource : new ArrayList<Resource>(resourceSet.getResources())) {
			if (toBeRemovedUri.equals(resource.getURI())) {
				if (resource.isLoaded()) {
					resource.unload();
				}
				resourceSet.getResources().remove(resource);	
			}
		}
	}


	public static boolean deleteEMFResource(EObject toBeDeletedEObject) {
		Resource toBeDeletedEResource = toBeDeletedEObject.eResource();
		try {
			// Deleting the file
			// NB. using EMF resource to delete the file doesn't work ! So using Resource plugin
			URI normalizedURI = toBeDeletedEResource.getURI();
			String platformResourcePathString = normalizedURI.toPlatformString(false); // no need to decode since Eclipse born URI
			IFile file = ConfPlugin.getWorkspaceRoot().getFile(new Path(platformResourcePathString));
			file.delete(true, null); // force,no progressMonitor
			
			// Unloading the EMF Resource
			if (toBeDeletedEResource.isLoaded()) {
				toBeDeletedEResource.unload();
				toBeDeletedEResource.getResourceSet().getResources().remove(toBeDeletedEResource);
			}
			
			return true;
		} catch (Exception ex) {
			// TODO log
			/*String msg = "Error loading ConfModel file " + confModelUri //$NON-NLS-1$
			+ ((modelRoot != null) ? " while looking for expected ConfModel of model " //$NON-NLS-1$
					+ modelRoot.eResource().getURI() : ""); //$NON-NLS-1$
			logger.(msg, ex);*/
			return false;
		}
	}
	
}
