/**
 * File:    DevtimeToRuntimePackageConverterXmiURIHandlerImpl.java
 * Created: 10.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.presentation.resource;

import java.util.Collection;
import java.util.HashMap;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.xmi.impl.URIHandlerImpl;


/**
 * Rather than  deresolving "platform:/plugin/*" URIs to relative ones (which would prevent
 * from further loading the file in EMF editors), deresolves them to runtime package URIs.
 * Used in ConfEditor to customize the save of conf files.
 * 
 * @version $Id: DevtimeToRuntimePackageConverterXmiURIHandlerImpl.java,v 1.2 2009-02-25 14:57:48 mdutoo Exp $
 * @author Marc Dutoo, Open Wide SA
 *
 */
public class DevtimeToRuntimePackageConverterXmiURIHandlerImpl extends URIHandlerImpl {
	
	private HashMap<URI,String> packageResourceToNsUriMap;

	/**
	 * Deresolves ecore URIs based on the packageResourceToNsUriMap built from the given set of resources.
	 * @param resources
	 */
	public DevtimeToRuntimePackageConverterXmiURIHandlerImpl(Collection<Resource> resources) {
		this(DevtimeToRuntimePackageConverterHelper.buildPackageResourceToNsUriMap(resources));
	}

	/**
	 * Deresolves ecore URIs based on the given set of resources.
	 * @param resources
	 */
	public DevtimeToRuntimePackageConverterXmiURIHandlerImpl(HashMap<URI,String> packageResourceToNsUriMap) {
		this.packageResourceToNsUriMap = packageResourceToNsUriMap;
	}
	

	@Override
	public URI deresolve(URI uri) {
		// NB. base URIs is set at save time by XMLHelperImpl
		
		// let's deresolve "platform:/plugin/*" to runtime EMF package URIs :
		if (uri.isPlatformPlugin()) {
			String uriFragmentString = uri.fragment();
			int uriFragmentLastSlashIndex = uriFragmentString.lastIndexOf("/"); //$NON-NLS-1$
			String packageFragmentPath = uriFragmentString.substring(0, uriFragmentLastSlashIndex);
			URI packageResourceUri = (packageFragmentPath.length() == 0) ?
					uri : uri.trimFragment().appendFragment(packageFragmentPath);
			
			String packageNsUri = packageResourceToNsUriMap.get(packageResourceUri);
			if (packageNsUri != null) {
				String slashPlusEObjectPath = uriFragmentString.substring(uriFragmentLastSlashIndex);
				return URI.createURI(packageNsUri + "#/" + slashPlusEObjectPath); //$NON-NLS-1$
			}
		}
		return super.deresolve(uri);
	}
}
