/*******************************************************************************
 * Copyright (c) 2020 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:
 *     Antonio Garcia-Dominguez - initial API and implementation
 ******************************************************************************/
package org.eclipse.hawk.ui.emf;

import java.util.HashSet;
import java.util.Set;

import org.eclipse.emf.ecore.EPackage;
import org.eclipse.hawk.core.IMetaModelResourceFactory;
import org.eclipse.hawk.core.IModelIndexer;
import org.eclipse.hawk.core.model.IHawkMetaModelResource;
import org.eclipse.hawk.emf.EMFWrapperFactory;
import org.eclipse.hawk.emf.metamodel.EMFMetaModelResource;
import org.eclipse.hawk.emf.metamodel.EMFMetaModelResourceFactory;
import org.eclipse.hawk.ui2.mmselectors.IHawkMetaModelResourceSelector;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.FilteredItemsSelectionDialog;

public class EPackageRegistrySelector implements IHawkMetaModelResourceSelector {

	@Override
	public boolean isApplicableTo(IModelIndexer indexer) {
		if (indexer.getMetaModelUpdater() != null) {
			return getEMFMetamodelResourceFactory(indexer) != null;
		}
		return false;
	}

	@Override
	public void selectMetamodels(Shell parentShell, IModelIndexer indexer) throws Exception {
		final FilteredItemsSelectionDialog dialog = new FilteredEPackageSelectionDialog(parentShell, true);

		int status = dialog.open();
		if (status == Window.OK) {
			Object[] result = dialog.getResult();
			if (result != null) {
				final IMetaModelResourceFactory factory = getEMFMetamodelResourceFactory(indexer);

				Set<IHawkMetaModelResource> resources = new HashSet<>(result.length);
				for (Object o : result) {
					String mmURI = (String) o;
					EPackage pkg = EPackage.Registry.INSTANCE.getEPackage(mmURI);
					EMFMetaModelResource r = new EMFMetaModelResource(pkg.eResource(), new EMFWrapperFactory(), factory);
					resources.add(r);
				}

				indexer.getMetaModelUpdater().insertMetamodels(resources, indexer);
			}
		}
	}

	private IMetaModelResourceFactory getEMFMetamodelResourceFactory(IModelIndexer indexer) {
		for (IMetaModelResourceFactory parser : indexer.getMetaModelParsers()) {
			if (parser instanceof EMFMetaModelResourceFactory) {
				return parser;
			}
		}
		return null;
	}
}
