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

import java.io.File;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.hawk.core.IModelIndexer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog;

public class WorkspaceSelector implements IHawkMetaModelResourceSelector {

	@Override
	public boolean isApplicableTo(IModelIndexer indexer) {
		return true;
	}

	@Override
	public void selectMetamodels(Shell parentShell, IModelIndexer indexer) throws Exception {
		FilteredResourcesSelectionDialog dialog = new FilteredResourcesSelectionDialog(parentShell,
			true, ResourcesPlugin.getWorkspace().getRoot(), IResource.FILE);
	
		String[] patterns = IHawkMetaModelResourceSelector.getKnownMetamodelFilePatterns(indexer);
		if (patterns.length > 0) {
			dialog.setInitialPattern(patterns[0], FilteredResourcesSelectionDialog.FULL_SELECTION);
		}
		dialog.setTitle("Add metamodel from workspace");
		dialog.setMessage("Select a metamodel file from the workspace");
		dialog.open();
		
		if (dialog.getReturnCode() == Window.OK){
			Object[] iFiles = dialog.getResult();
			File[] files = new File[iFiles.length];
			for (int i = 0; i < iFiles.length; i++) {
				files[i] = ((IFile)iFiles[i]).getLocation().toFile();
			}

			indexer.registerMetamodels(files);
		}
	}

}
