package org.eclipse.stp.sc.common.internal.viewers;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.wst.server.core.IModuleType;
import org.eclipse.wst.server.core.IRuntime;
import org.eclipse.wst.server.core.ServerCore;
import org.eclipse.wst.server.core.internal.Runtime;

public class FilterRuntimeContentProvider implements IStructuredContentProvider {

	protected String[] moduleTypes = null;
	protected String[] runtimeTypes = null;;
	
	/**
	 * constructor for the filter runtime content provider.
	 */
	public FilterRuntimeContentProvider() {		
	}
	
	public void setModuleTypes(String[] types) {
		moduleTypes = types;
	}
	
	
	public void setRuntimeTypes(String[] types) {
	    runtimeTypes = types;	
	}
	
	@SuppressWarnings("unchecked")
	public Object[] getElements(Object inputElement) {
		List list = new ArrayList();
		IRuntime[] runtimes = ServerCore.getRuntimes();
		if (runtimes != null) {
			int size = runtimes.length;
			for (int i = 0; i < size; i++) {
				if (filterRuntime(runtimes[i])) {
					continue;
				}
				if (!((Runtime)runtimes[i]).isPrivate())
					list.add(runtimes[i]);
			}
		}
		return list.toArray();
	}

	/**
	 * filter the runtime according to moduelType or runtimeType.
	 * @param runtime
	 * @return, true, if this runtime need to be filter out
	 */
	private boolean filterRuntime(IRuntime runtime) {
		if (moduleTypes == null && runtimeTypes == null) {
			//that means no filter has been setup. so we will show all runtimes
			return false;
		}
		//check for runtime types
		if (runtimeTypes != null) {
			for (String runtimeID : runtimeTypes) {
				if (runtimeID.equals(runtime.getId())) {
					return false;
				}
			}
		}
		IModuleType[] types = runtime.getRuntimeType().getModuleTypes();
		//check for module types
		if (moduleTypes != null) {
			for (String moduleType : moduleTypes) {
			    for (IModuleType type: types) {
			    	if (type.getId().equals(moduleType)) {
			    		return false;
			    	}
			    }
			}
		}
	    return true;	
	}
	public void dispose() {
	}

	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {

	}

}
