/*******************************************************************************
 * Copyright (c) 2011-2020 The University of York, Aston University.
 * 
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * This Source Code may also be made available under the following Secondary
 * Licenses when the conditions for such availability set forth in the Eclipse
 * Public License, v. 2.0 are satisfied: GNU General Public License, version 3.
 *
 * SPDX-License-Identifier: EPL-2.0 OR GPL-3.0
 *
 * Contributors:
 *     Konstantinos Barmpis - initial API and implementation
 *     Antonio Garcia-Dominguez - change to use registered EMF resource factories
 ******************************************************************************/
package org.eclipse.hawk.emf.model;

import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.Resource.Factory;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.hawk.core.IFileImporter;
import org.eclipse.hawk.core.IModelResourceFactory;
import org.eclipse.hawk.core.model.IHawkModelResource;
import org.eclipse.hawk.emf.EMFWrapperFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EMFModelResourceFactory implements IModelResourceFactory {

	private static final Logger LOGGER = LoggerFactory.getLogger(EMFModelResourceFactory.class);

	/**
	 * Property that can be set to a comma-separated list of extensions (e.g.
	 * ".railway,.myext") that should be supported in addition to the default ones
	 * (".xmi" and ".model"). Composite extensions are allowed (e.g. ".rail.way").
	 */
	public static final String PROPERTY_EXTRA_EXTENSIONS = "org.eclipse.hawk.emf.model.extraExtensions";

	private static final String TYPE = "org.eclipse.hawk.emf.metamodel.EMFModelParser";
	private static final String HUMAN_READABLE_NAME = "EMF Model Resource Factory";

	private Set<String> modelExtensions;

	public EMFModelResourceFactory() {
		modelExtensions = new HashSet<String>();

		for (String ext : Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().keySet()) {
			if (!Resource.Factory.Registry.DEFAULT_EXTENSION.equals(ext)) {
				modelExtensions.add("." + ext);
			}
		}
		modelExtensions.add(".xmi");
		modelExtensions.add(".model");

		// TODO is this still needed?
		final String sExtraExtensions = System.getProperty(PROPERTY_EXTRA_EXTENSIONS);
		if (sExtraExtensions != null) {
			String[] extraExtensions = sExtraExtensions.split(",");
			for (String extraExtension : extraExtensions) {
				modelExtensions.add(extraExtension);
			}
		}
	}

	@Override
	public final String getType() {
		return TYPE;
	}

	@Override
	public String getHumanReadableName() {
		return HUMAN_READABLE_NAME;
	}

	@Override
	public IHawkModelResource parse(IFileImporter importer, File f) {
		IHawkModelResource ret;
		Resource r = null;

		try {
			final ResourceSet resourceSet = new ResourceSetImpl();

			// Try to use the globally registered factory, use XMI factory as fallback
			final URI fileURI = URI.createFileURI(f.getCanonicalPath());
			final Factory factory = createResourceFactory(resourceSet, fileURI);
			r = factory.createResource(fileURI);
			r.load(createEMFLoadOptions());
			ret = new EMFModelResource(r, new EMFWrapperFactory(), this);
		} catch (Exception e) {
			LOGGER.error("Failed to parse " + f.getAbsolutePath(), e);
			ret = null;
		}

		return ret;
	}

	@Override
	public void shutdown() {
		// nothing to do
	}

	@Override
	public Set<String> getModelExtensions() {
		return modelExtensions;
	}

	protected Factory createResourceFactory(ResourceSet resourceSet, URI fileURI) {
		Factory factory = resourceSet.getResourceFactoryRegistry().getFactory(fileURI);
		if (factory == null) {
			return new XMIResourceFactoryImpl();
		} else {
			return factory;
		}
	}

	protected Map<?, ?> createEMFLoadOptions() {
		return Collections.emptyMap();
	}

	@Override
	public boolean canParse(File f) {
		String[] split = f.getPath().split("\\.");
		String extension = split[split.length - 1];
		return getModelExtensions().contains("." + extension);
	}
}
