/*
 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.drools.eclipse.wizard.project;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.drools.eclipse.DroolsEclipsePlugin;
import org.drools.eclipse.preferences.DroolsProjectPreferencePage;
import org.drools.eclipse.util.DroolsRuntime;
import org.drools.eclipse.util.DroolsRuntimeManager;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.kie.eclipse.runtime.AbstractRuntime.Version;
import org.kie.eclipse.runtime.IRuntime;
import org.kie.eclipse.runtime.IRuntimeManager;
import org.kie.eclipse.utils.FileUtils;
import org.kie.eclipse.wizard.project.AbstractKieEmptyProjectWizardPage;
import org.kie.eclipse.wizard.project.AbstractKieOnlineExampleProjectWizardPage;
import org.kie.eclipse.wizard.project.AbstractKieProjectStartWizardPage;
import org.kie.eclipse.wizard.project.AbstractKieProjectWizard;
import org.kie.eclipse.wizard.project.IKieProjectWizardPage;
import org.kie.eclipse.wizard.project.IKieSampleFilesProjectWizardPage;

/**
 * A wizard to create a new Drools project.
 */
public class NewDroolsProjectWizard extends AbstractKieProjectWizard {

    private EmptyDroolsProjectWizardPage emptyProjectPage;
    private SampleDroolsProjectWizardPage sampleFilesProjectPage;

    @Override
	protected void initializeDefaultPageImageDescriptor() {
        ImageDescriptor desc = DroolsEclipsePlugin.getImageDescriptor("icons/drools-large.PNG");
        setDefaultPageImageDescriptor(desc);
    }

    @Override
	protected void createOutputLocation(IJavaProject project, IProgressMonitor monitor)
            throws JavaModelException, CoreException {
        IFolder folder = FileUtils.createFolder(project, "target/classes", monitor);
        IPath path = folder.getFullPath();
        project.setOutputLocation(path, null);
    }

    @Override
	protected void createInitialContent(IJavaProject javaProject, IProgressMonitor monitor)
            throws CoreException, JavaModelException, IOException {
    	if (startPage.getInitialProjectContent() == IKieProjectWizardPage.SAMPLE_FILES_PROJECT) {
            if (sampleFilesProjectPage.shouldCreateJavaRuleFile()) {
                createRuleSampleLauncher(javaProject);
            }
            if (sampleFilesProjectPage.shouldCreateRuleFile()) {
                createRule(javaProject, monitor);
            }
            if (sampleFilesProjectPage.shouldCreateDecisionTableFile()) {
                createDecisionTable(javaProject, monitor);
            }
            if (sampleFilesProjectPage.shouldCreateJavaDecisionTableFile()) {
                createDecisionTableSampleLauncher(javaProject);
            }
            if (sampleFilesProjectPage.shouldCreateRuleFlowFile()) {
                createRuleFlow(javaProject, monitor);
            }
            if (sampleFilesProjectPage.shouldCreateJavaRuleFlowFile()) {
                createRuleFlowSampleLauncher(javaProject);
            }
			createKJarArtifacts(javaProject, monitor);
			createMavenArtifacts(javaProject, monitor);
    	}
    	else if (startPage.getInitialProjectContent() == IKieProjectWizardPage.EMPTY_PROJECT) {
    		createDefaultPackages(javaProject, monitor);
			createKJarArtifacts(javaProject, monitor);
			createMavenArtifacts(javaProject, monitor);
    	}
    	else {
    		super.createInitialContent(javaProject, monitor);
    	}
	    createLoggerFile(javaProject, monitor);
    }

    protected void addSourceFolders(IJavaProject project, IProgressMonitor monitor) throws JavaModelException, CoreException {
    	if (startPage.getInitialProjectContent()!=IKieProjectWizardPage.ONLINE_EXAMPLE_PROJECT) {
	        List<IClasspathEntry> list = new ArrayList<IClasspathEntry>();
	        list.addAll(Arrays.asList(project.getRawClasspath()));
	        addSourceFolder(project, list, "src/main/java", monitor);
            if (startPage.getRuntime().getVersion().getMajor()>=6) {
	        	addSourceFolder(project, list, "src/main/resources", monitor);
	        } else {
	        	addSourceFolder(project, list, "src/main/rules", monitor);
	        }
	        project.setRawClasspath((IClasspathEntry[]) list.toArray(new IClasspathEntry[list.size()]), null);
    	}
    }

    private void createDefaultPackages(IJavaProject project, IProgressMonitor monitor) throws CoreException {
		IFolder folder = project.getProject().getFolder("src/main/java/com/sample");
		FileUtils.createFolder(folder, monitor);
		folder = project.getProject().getFolder("src/main/resources/com/sample/rules");
		FileUtils.createFolder(folder, monitor);
		folder = project.getProject().getFolder("src/main/resources/com/sample/dtables");
		FileUtils.createFolder(folder, monitor);
		folder = project.getProject().getFolder("src/main/resources/com/sample/process");
		FileUtils.createFolder(folder, monitor);
    }

    private void createLoggerFile(IJavaProject project, IProgressMonitor monitor) throws CoreException {
	    String fileName = "org/drools/eclipse/wizard/project/logback-test.xml.template";
        IFolder folder = project.getProject().getFolder("src/main/resources");
        FileUtils.createFolder(folder, monitor);
        IFile file = folder.getFile("logback-test.xml");
        InputStream inputstream = getClass().getClassLoader().getResourceAsStream(fileName);
        if (!file.exists()) {
            file.create(inputstream, true, monitor);
        } else {
            file.setContents(inputstream, true, false, monitor);
        }
    }

    @Override
	protected void createMavenArtifacts(IJavaProject project, IProgressMonitor monitor) {
        try {
        	String projectName = project.getProject().getName();
        	String runtimeVersion = startPage.getRuntime().getVersion().toString();
            String groupId = "com.sample";
            String artifactId = projectName;
            String version = "1.0.0-SNAPSHOT";
            boolean shouldCreateMavenProject = false;
        	if (startPage.getInitialProjectContent() == IKieProjectWizardPage.SAMPLE_FILES_PROJECT) {
        		groupId = sampleFilesProjectPage.getPomGroupId();
        		artifactId = sampleFilesProjectPage.getPomArtifactId();
        		version = sampleFilesProjectPage.getPomVersion();
        		shouldCreateMavenProject = sampleFilesProjectPage.shouldCreateMavenProject();
        	}
        	else if (startPage.getInitialProjectContent() == IKieProjectWizardPage.EMPTY_PROJECT) {
        		groupId = emptyProjectPage.getPomGroupId();
        		artifactId = emptyProjectPage.getPomArtifactId();
        		version = emptyProjectPage.getPomVersion();
        		shouldCreateMavenProject = emptyProjectPage.shouldCreateMavenProject();
        	}

			FileUtils.createProjectFile(project, monitor, FileUtils.generatePomProperties(groupId, artifactId, version), "src/main/resources/META-INF/maven", "pom.properties");

			if (shouldCreateMavenProject) {
				String fileName = "org/drools/eclipse/wizard/project/maven-pom.xml.template";
				InputStream inputstream = getClass().getClassLoader().getResourceAsStream(fileName);
				FileUtils.createProjectFile(project, monitor,
	            		FileUtils.generatePom(inputstream, runtimeVersion, groupId, artifactId, version),
	            		null, "pom.xml");
			}
		}
		catch (CoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    @Override
	protected void createKJarArtifacts(IJavaProject project, IProgressMonitor monitor) {
        try {
	        if (startPage.getRuntime().getVersion().getMajor()>=6) {
	        	FileUtils.createProjectFile(project, monitor, generateKModule(), "src/main/resources/META-INF", "kmodule.xml");

	        	String projectName = project.getProject().getName();
	            String groupId = "com.sample";
	            String artifactId = projectName;
	            String version = "1.0.0-SNAPSHOT";
				FileUtils.createProjectFile(project, monitor, FileUtils.generatePomProperties(groupId, artifactId, version), "src/main/resources/META-INF/maven", "pom.properties");
	        }
		}
		catch (CoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    private InputStream generateKModule() {
    	StringBuilder sb = new StringBuilder();
    	sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    	sb.append("<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">\n");

        if (sampleFilesProjectPage.shouldCreateRuleFile() || sampleFilesProjectPage.shouldCreateJavaRuleFile()) {
        	sb.append("    <kbase name=\"rules\" packages=\"com.sample.rules\">\n");
        	sb.append("        <ksession name=\"ksession-rules\"/>\n");
        	sb.append("    </kbase>\n");
        }
        if (sampleFilesProjectPage.shouldCreateDecisionTableFile() || sampleFilesProjectPage.shouldCreateJavaDecisionTableFile()) {
        	sb.append("    <kbase name=\"dtables\" packages=\"com.sample.dtables\">\n");
        	sb.append("        <ksession name=\"ksession-dtables\"/>\n");
        	sb.append("    </kbase>\n");
        }
        if (sampleFilesProjectPage.shouldCreateRuleFlowFile() || sampleFilesProjectPage.shouldCreateJavaRuleFlowFile()) {
        	sb.append("    <kbase name=\"process\" packages=\"com.sample.process\">\n");
        	sb.append("        <ksession name=\"ksession-process\"/>\n");
        	sb.append("    </kbase>\n");
        }

        sb.append("</kmodule>\n");

        return new ByteArrayInputStream(sb.toString().getBytes());
    }

    /**
     * Create the sample rule launcher file.
     */
    private void createRuleSampleLauncher(IJavaProject project)
            throws JavaModelException, IOException {

        Version version = startPage.getRuntime().getVersion();
        if (version.getMajor()==4) {
            createProjectJavaFile(project, "org/drools/eclipse/wizard/project/RuleLauncherSample_4.java.template", "DroolsTest.java");
        } else if (version.getMajor()==5) {
            createProjectJavaFile(project, "org/drools/eclipse/wizard/project/RuleLauncherSample_5.java.template", "DroolsTest.java");
        } else if (version.getMajor()>=6) {
            createProjectJavaFile(project, "org/drools/eclipse/wizard/project/RuleLauncherSample_6.java.template", "DroolsTest.java");
        }
    }

    /**
     * Create the sample decision table launcher file.
     */
    private void createDecisionTableSampleLauncher(IJavaProject project)
            throws JavaModelException, IOException {

        Version version = startPage.getRuntime().getVersion();
        if (version.getMajor()==4) {
            createProjectJavaFile(project, "org/drools/eclipse/wizard/project/DecisionTableLauncherSample_4.java.template", "DecisionTableTest.java");
        } else if (version.getMajor()==5) {
            createProjectJavaFile(project, "org/drools/eclipse/wizard/project/DecisionTableLauncherSample_5.java.template", "DecisionTableTest.java");
        } else if (version.getMajor()>=6) {
            createProjectJavaFile(project, "org/drools/eclipse/wizard/project/DecisionTableLauncherSample_6.java.template", "DecisionTableTest.java");
        }
    }

	private void createProjectJavaFile(IJavaProject project, String templateFile, String javaFile) throws JavaModelException, IOException {
		IFolder folder = project.getProject().getFolder("src/main/java");
        IPackageFragmentRoot packageFragmentRoot = project.getPackageFragmentRoot(folder);
        IPackageFragment packageFragment = packageFragmentRoot.createPackageFragment("com.sample", true, null);
        InputStream inputstream = getClass().getClassLoader().getResourceAsStream(templateFile);
        packageFragment.createCompilationUnit(javaFile, new String(FileUtils.readStream(inputstream)), true, null);
	}

	private void createProjectFile(IJavaProject project, IProgressMonitor monitor, String templateFile, String folderName, String fileName) throws CoreException {
        InputStream inputstream = getClass().getClassLoader().getResourceAsStream(templateFile);
        FileUtils.createProjectFile(project, monitor, inputstream, folderName, fileName);
	}

	/**
     * Create the sample rule file.
     */
    private void createRule(IJavaProject project, IProgressMonitor monitor) throws CoreException {
        if (startPage.getRuntime().getVersion().getMajor()>=6) {
        	FileUtils.createFolder(project, "src/main/resources/com/sample/rules", monitor);
            createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/Sample.drl.template", "src/main/resources/com/sample/rules", "Sample.drl");
        } else {
            createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/Sample.drl.template", "src/main/rules", "Sample.drl");
        }
    }

    /**
     * Create the sample decision table file.
     */
    private void createDecisionTable(IJavaProject project, IProgressMonitor monitor) throws CoreException {
        if (startPage.getRuntime().getVersion().getMajor()>=6) {
        	FileUtils.createFolder(project, "src/main/resources/com/sample/dtables", monitor);
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/Sample.xls.template", "src/main/resources/com/sample/dtables", "Sample.xls");
    	} else {
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/Sample.xls.template", "src/main/rules", "Sample.xls");
    	}
    }

    /**
     * Create the sample RuleFlow file.
     */
    private void createRuleFlow(IJavaProject project, IProgressMonitor monitor) throws CoreException {

        Version version = startPage.getRuntime().getVersion();
        if (version.getMajor()==4) {
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/ruleflow_4.rf.template", "src/main/rules", "ruleflow.rf");
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/ruleflow_4.rfm.template", "src/main/rules", "ruleflow.rfm");
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/ruleflow_4.drl.template", "src/main/rules", "ruleflow.drl");
        } else if (version.getMajor()==5 && version.getMinor()==0) {
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/ruleflow.rf.template", "src/main/rules", "ruleflow.rf");
        } else if (version.getMajor()==5) {
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/sample.bpmn.template", "src/main/rules", "sample.bpmn");
        } else {
        	FileUtils.createFolder(project, "src/main/resources/com/sample/process", monitor);
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/sample.bpmn.template", "src/main/resources/com/sample/process", "sample.bpmn");
        }
    }

    /**
     * Create the sample RuleFlow launcher file.
     */
    private void createRuleFlowSampleLauncher(IJavaProject project)
            throws JavaModelException, IOException {

        String s;
        Version version = startPage.getRuntime().getVersion();
        if (version.getMajor()==4) {
            s = "org/drools/eclipse/wizard/project/RuleFlowLauncherSample_4.java.template";
        } else if (version.getMajor()==5 && version.getMinor()==0) {
            s = "org/drools/eclipse/wizard/project/RuleFlowLauncherSample.java.template";
        } else if (version.getMajor()==5) {
            s = "org/drools/eclipse/wizard/project/ProcessLauncherSample_bpmn_5.java.template";
        } else {
            s = "org/drools/eclipse/wizard/project/ProcessLauncherSample_bpmn_6.java.template";
        }
        createProjectJavaFile(project, s, "ProcessTest.java");
    }

	/* (non-Javadoc)
	 * @see org.kie.eclipse.wizard.project.AbstractKieProjectWizard#createStartPage(java.lang.String)
	 * Create the Wizard Start Page
	 */
	@Override
	protected IKieProjectWizardPage createStartPage(String pageId) {
		return new AbstractKieProjectStartWizardPage(pageId) {
			@Override
			public String getTitle() {
				return "Create New Drools Project";
			}
		};
	}

	/* (non-Javadoc)
	 * @see org.kie.eclipse.wizard.project.AbstractKieProjectWizard#createEmptyProjectPage(java.lang.String)
	 * Create the Empty Project Wizard Page
	 */
	@Override
	protected IKieProjectWizardPage createEmptyProjectPage(String pageId) {
		emptyProjectPage = new EmptyDroolsProjectWizardPage(EMPTY_PROJECT_PAGE);
		return emptyProjectPage;
	}

	/* (non-Javadoc)
	 * @see org.kie.eclipse.wizard.project.AbstractKieProjectWizard#createSampleFilesProjectPage(java.lang.String)
	 * Create the Sample Files Project Wizard Page
	 */
	@Override
	protected IKieProjectWizardPage createSampleFilesProjectPage(String pageId) {
		sampleFilesProjectPage = new SampleDroolsProjectWizardPage(SAMPLE_FILES_PROJECT_PAGE);
		return sampleFilesProjectPage;
	}

	/* (non-Javadoc)
	 * @see org.kie.eclipse.wizard.project.AbstractKieProjectWizard#createOnlineExampleProjectPage(java.lang.String)
	 * Create the Online Example Project Wizard Page
	 */
	@Override
	protected IKieProjectWizardPage createOnlineExampleProjectPage(String pageId) {
		return new AbstractKieOnlineExampleProjectWizardPage(ONLINE_EXAMPLE_PROJECT_PAGE) {
			@Override
			public String getTitle() {
				return "Create Drools Projects from Online Examples";
			}

			@Override
			public String getDescription() {
				return "Select Drools Example Projects";
			}

			@Override
			public IRuntimeManager getRuntimeManager() {
				return DroolsRuntimeManager.getDefault();
			}

			@Override
			public String getProductId() {
				return "drools";
			}
		};
	}

	/**
	 * Implementation for the Empty Project Wizard Page
	 */
	class EmptyDroolsProjectWizardPage extends AbstractKieEmptyProjectWizardPage implements IKieSampleFilesProjectWizardPage {

		public EmptyDroolsProjectWizardPage(String pageName) {
			super(pageName);
			setTitle("Create New Empty Drools Project");
			setDescription("Select the type of Drools Project");
		}

		@Override
		protected void createControls(Composite parent) {
		}

		@Override
		public IRuntimeManager getRuntimeManager() {
			return DroolsRuntimeManager.getDefault();
		}

		@Override
		protected IRuntime createRuntime() {
			return new DroolsRuntime();
		}

		@Override
		public int showRuntimePreferenceDialog() {
	        return PreferencesUtil.createPreferenceDialogOn(getShell(),
	                DroolsProjectPreferencePage.PREF_ID,
	                new String[] { DroolsProjectPreferencePage.PROP_ID }, null).open();
		}

		@Override
		public String getProductName() {
			return "Drools";
		}

		@Override
		public String getProductId() {
			return "drools";
		}
	}

	/**
	 * Implementation for the Sample Files Project Wizard Page
	 */
	class SampleDroolsProjectWizardPage extends EmptyDroolsProjectWizardPage {
	    private boolean addSampleRule = true;
	    private boolean addSampleDecisionTableCode = true;
	    private boolean addSampleRuleFlow = true;

		public SampleDroolsProjectWizardPage(String pageName) {
			super(pageName);
			setTitle("Create New Drools Project with Sample Files");
			setDescription("Select the sample files to be included");
		}

		@Override
		protected void createControls(Composite parent) {
			Composite composite = new Composite(parent, SWT.NONE);
	        composite.setLayout(new GridLayout(1, false));
	        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
	        gd.verticalIndent = 10;
	        gd.horizontalIndent = 10;
	        composite.setLayoutData(gd);
	        composite.setLayoutData(gd);

	        final Button addSampleRuleButton = createCheckBox(composite,
	            "Add a sample HelloWorld rule file to this project.");
	        addSampleRuleButton.setSelection(addSampleRule);
	        addSampleRuleButton.addSelectionListener(new SelectionAdapter() {
	            @Override
				public void widgetSelected(SelectionEvent e) {
	                addSampleRule = ((Button) e.widget).getSelection();
	            }
	        });

	        final Button addSampleDecisionTableCodeButton = createCheckBox(composite,
	            "Add a sample HelloWorld decision table file to this project.");
	        addSampleDecisionTableCodeButton.setSelection(addSampleDecisionTableCode);
	        addSampleDecisionTableCodeButton.addSelectionListener(new SelectionAdapter() {
	            @Override
				public void widgetSelected(SelectionEvent e) {
	                addSampleDecisionTableCode = ((Button) e.widget).getSelection();
	            }
	        });

	        final Button addSampleRuleFlowButton = createCheckBox(composite,
	            "Add a sample HelloWorld process file to this project.");
	        addSampleRuleFlowButton.setSelection(addSampleRuleFlow);
	        addSampleRuleFlowButton.addSelectionListener(new SelectionAdapter() {
	            @Override
				public void widgetSelected(SelectionEvent e) {
	                addSampleRuleFlow = ((Button) e.widget).getSelection();
	            }
	        });
		}

	    public boolean shouldCreateRuleFile() {
	        return addSampleRule;
	    }

	    public boolean shouldCreateJavaRuleFile() {
	        return addSampleRule; //addSampleJavaRuleCode;
	    }

	    public boolean shouldCreateDecisionTableFile() {
	        return addSampleDecisionTableCode;
	    }

	    public boolean shouldCreateJavaDecisionTableFile() {
	        return addSampleDecisionTableCode; //addSampleJavaDecisionTableCode;
	    }

	    public boolean shouldCreateRuleFlowFile() {
	        return addSampleRuleFlow;
	    }

	    public boolean shouldCreateJavaRuleFlowFile() {
	        return addSampleRuleFlow; //addSampleJavaRuleFlowCode;
	    }
	}
}


/*
 * Copyright 2015 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

package org.kie.eclipse.wizard.project;

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

import org.eclipse.equinox.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.p2.metadata.IRequirement;
import org.eclipse.equinox.p2.metadata.expression.IMatchExpression;
import org.eclipse.equinox.p2.query.IQueryResult;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ICheckStateProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;

public class IUTreeViewer extends CheckboxTreeViewer {

	private List<SelectionListener> selectionListeners = new ArrayList<SelectionListener>();

	class IUTreeItem {
    	final private IInstallableUnit iu;
    	final private IUTreeViewer.IUTreeItem parent;
    	final private IUTreeViewer.IUTreeContentProvider provider;
    	private Collection<IUTreeViewer.IUTreeItem> children;
    	private boolean checked;

    	public IUTreeItem(IUTreeViewer.IUTreeContentProvider provider, IUTreeViewer.IUTreeItem parent, IInstallableUnit iu) {
    		this.provider = provider;
    		this.parent = parent;
    		this.iu = iu;
    		checked = false;
    	}

    	public boolean isChecked() {
    		if (parent==null) {
    			for (IUTreeViewer.IUTreeItem child : getChildren()) {
    				if (child.isChecked())
    					return true;
    			}
    			return false;
    		}
    		return checked;
    	}

    	public boolean isGrayed() {
    		if (parent==null) {
    			int countChecked = 0;
    			for (IUTreeViewer.IUTreeItem child : getChildren()) {
    				if (child.isChecked())
    					++countChecked;
    			}
    			return countChecked>0 && countChecked!=children.size();
    		}
    		return false;
    	}

    	public void setChecked(boolean checked) {
    		this.checked = checked;
    	}

    	public IUTreeViewer.IUTreeItem getParent() {
    		return parent;
    	}

		public Collection<IUTreeViewer.IUTreeItem> getChildren() {
			if (children==null) {
		    	children = new ArrayList<IUTreeViewer.IUTreeItem>();
				if (parent==null) {
					for (IRequirement r : iu.getRequirements()) {
						for (IInstallableUnit riu : provider.getInstallableUnits()) {
							if (r.isMatch(riu)) {
								IMatchExpression<IInstallableUnit> me = r.getFilter();
								if (me!=null) {
									if (me.isMatch(riu))
										children.add(new IUTreeItem(provider, this, riu));
								}
								else
									children.add(new IUTreeItem(provider, this, riu));
							}
						}
					}
				}
			}
			return children;
		}

		public String getName() {
			if (parent==null)
				return iu.getProperty(IInstallableUnit.PROP_NAME);
			return iu.getProperty(IInstallableUnit.PROP_NAME) + "  (v" + iu.getVersion() + ")";
		}

		public void setSubtreeChecked(boolean checked) {
			this.checked = checked;
			if (parent==null) {
				for (IUTreeItem child : getChildren()) {
					child.checked = checked;
				}
			}
		}

		public int getSubtreeCheckedCount() {
			if (parent==null) {
				int count = 0;
				for (IUTreeItem child : getChildren()) {
					count += child.checked ? 1 : 0;
				}
				return count;
			}
			return checked ? 1 : 0;
		}
    }

    class IUTreeContentProvider implements ITreeContentProvider {
    	Collection<IUTreeViewer.IUTreeItem> elements = new ArrayList<IUTreeViewer.IUTreeItem>();
    	Collection<IInstallableUnit> installableUnits = new ArrayList<IInstallableUnit>();

		@Override
		public void dispose() {
		}

		public Collection<IInstallableUnit> getInstallableUnits() {
			return installableUnits;
		}

		@Override
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
			elements.clear();
			installableUnits.clear();
			if  (newInput instanceof IQueryResult) {
				for (Object o : (IQueryResult<?>)newInput) {
					if (o instanceof IInstallableUnit) {
						IInstallableUnit iu = (IInstallableUnit) o;
						installableUnits.add(iu);
						if (isGroup(iu)) {
							elements.add(new IUTreeItem(this, null, iu));
						}
					}
				}
			}
		}

		@Override
		public Object[] getElements(Object inputElement) {
			return elements.toArray(new Object[elements.size()]);
		}

		@Override
		public Object[] getChildren(Object parentElement) {
			if (parentElement instanceof IUTreeViewer.IUTreeItem) {
				Collection<IUTreeViewer.IUTreeItem> children = ((IUTreeViewer.IUTreeItem)parentElement).getChildren();
				return children.toArray(new Object[children.size()]);
			}
			return null;
		}

		@Override
		public Object getParent(Object element) {
			if (element instanceof IUTreeViewer.IUTreeItem)
				return ((IUTreeViewer.IUTreeItem)element).getParent();
			return null;
		}

		@Override
		public boolean hasChildren(Object element) {
			if (element instanceof IUTreeViewer.IUTreeItem)
				return isGroup(((IUTreeViewer.IUTreeItem)element).iu);
			return false;
		}

		public boolean isGroup(IInstallableUnit iu) {
			String isGroup = iu==null ? null : iu.getProperty("org.eclipse.equinox.p2.type.group");
			return Boolean.valueOf(isGroup);
		}
    }

    class IUTreeLabelProvider implements ILabelProvider {

		@Override
		public void addListener(ILabelProviderListener listener) {
		}

		@Override
		public void dispose() {
		}

		@Override
		public boolean isLabelProperty(Object element, String property) {
			return false;
		}

		@Override
		public void removeListener(ILabelProviderListener listener) {
		}

		@Override
		public Image getImage(Object element) {
			return null;
		}

		@Override
		public String getText(Object element) {
			if (element instanceof IUTreeViewer.IUTreeItem)
				return ((IUTreeViewer.IUTreeItem)element).getName();
			return element.toString();
		}
    }

    class IUTreeCheckStateListener implements ICheckStateListener {

    	private IUTreeViewer treeViewer;
    	public IUTreeCheckStateListener(IUTreeViewer treeViewer) {
    		this.treeViewer = treeViewer;
    	}

		@Override
		public void checkStateChanged(CheckStateChangedEvent event) {
			boolean checked = event.getChecked();
			Object element = event.getElement();
			if (element instanceof IUTreeItem) {
				IUTreeItem item = (IUTreeItem)element;
				updateDescendents(item, checked);
				updateAncestors(item.getParent(), checked);

				if (item.parent!=null)
					item = item.parent;

				for (Object e : treeViewer.getElements()) {
					if (e instanceof IUTreeItem) {
						if (e != item)
							updateDescendents((IUTreeItem)e, false);
					}
				}
			}
		}

		void updateDescendents(IUTreeItem item, boolean checked) {
			for (IUTreeItem child : item.getChildren()) {
				updateDescendents(child,checked);
			}
			item.setSubtreeChecked(checked);
			treeViewer.setSubtreeChecked(item, checked);

			treeViewer.setChecked(item, checked);
			treeViewer.setGrayed(item, false);
		}

		void updateAncestors(IUTreeItem item, boolean checked) {
			while (item!=null) {
				int checkedCount = item.getSubtreeCheckedCount();
				int size = item.getChildren().size();
				if (checkedCount==0) {
					treeViewer.setChecked(item, false);
					item.setChecked(false);
					checked = true;
				}
				else if (checkedCount==size) {
					treeViewer.setChecked(item, true);
					treeViewer.setGrayed(item, false);
					item.setChecked(true);
				}
				else {
					treeViewer.setGrayChecked(item, true);
					item.setChecked(true);
				}
				item = item.getParent();
			}
		}
	};

    public IUTreeViewer(Composite parent, int style) {
		super(parent, style);
		final Tree tree = getTree();
		GridData gd = new GridData(GridData.FILL_BOTH);
		gd.minimumHeight = 3 * tree.getItemHeight();
		tree.setLayoutData(gd);
	}

    public void initialize() {
		setContentProvider(new IUTreeContentProvider());
		setCheckStateProvider(new ICheckStateProvider() {

			@Override
			public boolean isChecked(Object element) {
				if (element instanceof IUTreeViewer.IUTreeItem)
					return ((IUTreeViewer.IUTreeItem)element).isChecked();
				return false;
			}

			@Override
			public boolean isGrayed(Object element) {
				if (element instanceof IUTreeViewer.IUTreeItem)
					return ((IUTreeViewer.IUTreeItem)element).isGrayed();
				return false;
			}

		});
		setLabelProvider(new IUTreeLabelProvider());

		final Tree tree = getTree();

		tree.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (tree.getSelectionCount()==1) {
					IUTreeItem item = (IUTreeItem) tree.getSelection()[0].getData();
					e.data = item.iu;
					for (SelectionListener l : selectionListeners) {
						l.widgetSelected(e);
					}
				}
			}
		});

		addCheckStateListener(new IUTreeCheckStateListener(this));
    }

    /**
     * Returns only the installable units that are features, ignoring feature groups.
     *
     * @return
     */
    public List<IInstallableUnit> getSelectedIUs(){
    	List<IInstallableUnit> result = new ArrayList<IInstallableUnit>();
    	for (Object o : getCheckedElements()) {
    		if (o instanceof IUTreeItem) {
    			IUTreeItem item = (IUTreeItem) o;
	    		if (item.parent!=null)
	    			result.add(item.iu);
    		}
    	}
    	return result;
    }

    public Object[] getElements() {
    	return ((IUTreeContentProvider)getContentProvider()).getElements(null);
    }

    public void addSelectionListener(SelectionListener listener) {
    	if (!selectionListeners.contains(listener))
    		selectionListeners.add(listener);
    }

    public void removeSelectionListener(SelectionListener listener) {
    	if (selectionListeners.contains(listener))
    		selectionListeners.remove(listener);
    }

    public void dispose() {
    	if (getTree()!=null && !getTree().isDisposed()) {
    		getTree().dispose();
    	}
    }
}


/*
 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.guvnor.tools.actions;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.guvnor.tools.Activator;
import org.guvnor.tools.utils.ActionUtils;
import org.guvnor.tools.utils.PlatformUtils;
import org.guvnor.tools.wizards.AddResourceWizard;

/**
 * Adds a new resource to Guvnor.
 */
public class AddAction implements IObjectActionDelegate {

    private IStructuredSelection selectedItems;
    private IWorkbenchPart targetPart;

    public AddAction() {
        super();
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction, org.eclipse.ui.IWorkbenchPart)
     */
    public void setActivePart(IAction action, IWorkbenchPart targetPart) {
        this.targetPart = targetPart;
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
     */
    public void run(IAction action) {
        assert(targetPart != null && selectedItems != null);
        AddResourceWizard wiz = new AddResourceWizard();
        wiz.init(Activator.getDefault().getWorkbench(), selectedItems);
        WizardDialog dialog = new WizardDialog(targetPart.getSite().getShell(), wiz);
        dialog.create();
        if (dialog.open() == WizardDialog.OK) {
            PlatformUtils.refreshRepositoryView();
        }
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
     */
    public void selectionChanged(IAction action, ISelection selection) {
        boolean validResourceSet = ActionUtils.checkResourceSet(selection, false);
        if (validResourceSet) {
            action.setEnabled(true);
            selectedItems = (IStructuredSelection)selection;
        } else {
            action.setEnabled(false);
            selectedItems = null;
        }
    }
}


/*
 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.drools.eclipse.flow.common.editor;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.EventObject;

import org.drools.eclipse.DroolsEclipsePlugin;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IStorage;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.SWTGraphics;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.ContextMenuProvider;
import org.eclipse.gef.DefaultEditDomain;
import org.eclipse.gef.EditPartFactory;
import org.eclipse.gef.KeyHandler;
import org.eclipse.gef.KeyStroke;
import org.eclipse.gef.LayerConstants;
import org.eclipse.gef.editparts.LayerManager;
import org.eclipse.gef.editparts.ScalableRootEditPart;
import org.eclipse.gef.editparts.ZoomManager;
import org.eclipse.gef.palette.PaletteRoot;
import org.eclipse.gef.ui.actions.ActionRegistry;
import org.eclipse.gef.ui.actions.AlignmentAction;
import org.eclipse.gef.ui.actions.DirectEditAction;
import org.eclipse.gef.ui.actions.GEFActionConstants;
import org.eclipse.gef.ui.actions.ToggleGridAction;
import org.eclipse.gef.ui.parts.GraphicalEditorWithPalette;
import org.eclipse.gef.ui.parts.GraphicalViewerKeyHandler;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IStorageEditorInput;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;

/**
 * Abstract implementation of a graphical editor.
 */
public abstract class GenericModelEditor extends GraphicalEditorWithPalette { // implements ITabbedPropertySheetPageContributor {

    private Object model;
    private boolean savePreviouslyNeeded = false;
    private KeyHandler sharedKeyHandler;
    private PaletteRoot root;
    private OverviewOutlinePage overviewOutlinePage;

    public GenericModelEditor() {
        setEditDomain(new DefaultEditDomain(this));
    }

    protected void setModel(Object model) {
        this.model = model;
    }

    public Object getModel() {
        return model;
    }

    @SuppressWarnings("unchecked")
    protected void createActions() {
        super.createActions();
        ActionRegistry registry = getActionRegistry();

        IAction action = new DirectEditAction((IWorkbenchPart) this);
        registry.registerAction(action);
        getSelectionActions().add(action.getId());

        action = new AlignmentAction((IWorkbenchPart) this,
                PositionConstants.LEFT);
        registry.registerAction(action);
        getSelectionActions().add(action.getId());

        action = new AlignmentAction((IWorkbenchPart) this,
                PositionConstants.CENTER);
        registry.registerAction(action);
        getSelectionActions().add(action.getId());

        action = new AlignmentAction((IWorkbenchPart) this,
                PositionConstants.RIGHT);
        registry.registerAction(action);
        getSelectionActions().add(action.getId());

        action = new AlignmentAction((IWorkbenchPart) this,
                PositionConstants.TOP);
        registry.registerAction(action);
        getSelectionActions().add(action.getId());

        action = new AlignmentAction((IWorkbenchPart) this,
                PositionConstants.MIDDLE);
        registry.registerAction(action);
        getSelectionActions().add(action.getId());

        action = new AlignmentAction((IWorkbenchPart) this,
                PositionConstants.BOTTOM);
        registry.registerAction(action);
        getSelectionActions().add(action.getId());
    }

    public void commandStackChanged(EventObject event) {
        if (isDirty()) {
            if (!savePreviouslyNeeded()) {
                setSavePreviouslyNeeded(true);
                firePropertyChange(IEditorPart.PROP_DIRTY);
            }
        } else {
            setSavePreviouslyNeeded(false);
            firePropertyChange(IEditorPart.PROP_DIRTY);
        }
        super.commandStackChanged(event);
    }

    protected abstract void writeModel(OutputStream os) throws IOException;

    protected void configureGraphicalViewer() {
        super.configureGraphicalViewer();
        getGraphicalViewer().setRootEditPart(new ScalableRootEditPart());
        getGraphicalViewer().setEditPartFactory(createEditPartFactory());
        getGraphicalViewer().setKeyHandler(
                new GraphicalViewerKeyHandler(getGraphicalViewer())
                        .setParent(getCommonKeyHandler()));

        IAction showGrid = new ToggleGridAction(getGraphicalViewer());
        getActionRegistry().registerAction(showGrid);

        ContextMenuProvider provider = new GenericContextMenuProvider(
                getGraphicalViewer(), getActionRegistry());
        getGraphicalViewer().setContextMenu(provider);
        getSite().registerContextMenu("org.drools.eclipse.flow.editor.contextmenu",
                provider, getGraphicalViewer());
    }

    protected abstract EditPartFactory createEditPartFactory();

    protected void initializeGraphicalViewer() {
        getGraphicalViewer().setContents(model);
    }

    public void doSave(IProgressMonitor monitor) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            writeModel(out);
            IFile file = ((IFileEditorInput) getEditorInput()).getFile();
            file.setContents(new ByteArrayInputStream(out.toByteArray()), true,
                    false, monitor);
            out.close();
            getCommandStack().markSaveLocation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doSaveAs() {
        SaveAsDialog dialog = new SaveAsDialog(getSite().getWorkbenchWindow()
                .getShell());
        dialog.setOriginalFile(((IFileEditorInput) getEditorInput()).getFile());
        dialog.open();
        IPath path = dialog.getResult();

        if (path == null) {
            return;
        }

        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        final IFile file = workspace.getRoot().getFile(path);

        WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
            public void execute(final IProgressMonitor monitor)
                    throws CoreException {
                try {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    writeModel(out);
                    file.create(new ByteArrayInputStream(out.toByteArray()),
                            true, monitor);
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        try {
            new ProgressMonitorDialog(getSite().getWorkbenchWindow().getShell())
                    .run(false, true, op);
            setInput(new FileEditorInput(file));
            getCommandStack().markSaveLocation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected KeyHandler getCommonKeyHandler() {
        if (sharedKeyHandler == null) {
            sharedKeyHandler = new KeyHandler();
            sharedKeyHandler
                    .put(KeyStroke.getPressed(SWT.DEL, 127, 0),
                            getActionRegistry().getAction(
                                    ActionFactory.DELETE.getId()));
            sharedKeyHandler.put(KeyStroke.getPressed(SWT.F2, 0),
                    getActionRegistry().getAction(
                            GEFActionConstants.DIRECT_EDIT));
        }
        return sharedKeyHandler;
    }

    public boolean isDirty() {
        return isSaveOnCloseNeeded();
    }

    public boolean isSaveAsAllowed() {
        return true;
    }

    public boolean isSaveOnCloseNeeded() {
        return getCommandStack().isDirty();
    }

    private boolean savePreviouslyNeeded() {
        return savePreviouslyNeeded;
    }

    private void setSavePreviouslyNeeded(boolean value) {
        savePreviouslyNeeded = value;
    }

    protected PaletteRoot getPaletteRoot() {
        if (root == null) {
            root = createPalette();
        }
        return root;
    }

    protected abstract PaletteRoot createPalette();

    protected void setInput(IEditorInput input) {
        super.setInput(input);

        if (input instanceof IFileEditorInput) {
            IFile file = getFile();
            if (file != null) {
                setPartName(file.getName());
            }
            try {
                InputStream is = file.getContents(false);
                createModel(is);
            } catch (Throwable t) {
                DroolsEclipsePlugin.log(t);
            }
        } else if (input instanceof IStorageEditorInput) {
            try {
                IStorage storage = ((IStorageEditorInput) input).getStorage();
                setPartName(storage.getName());
                InputStream is = storage.getContents();
                createModel(is);
            } catch (Throwable t) {
                DroolsEclipsePlugin.log(t);
            }
        }

        if (getGraphicalViewer() != null) {
            initializeGraphicalViewer();
        }
    }

    public IFile getFile() {
        IEditorInput input = getEditorInput();
        if (!(input instanceof IFileEditorInput)) {
            return null;
        }
        return ((IFileEditorInput) getEditorInput()).getFile();
    }

    public IProject getProject() {
        IFile file = getFile();
        if (file != null) {
            return file.getProject();
        }
        return null;
    }

    public IJavaProject getJavaProject() {
        IProject project = getProject();
        if (project != null) {
            try {
                if (project.getNature("org.eclipse.jdt.core.javanature") != null) {
                    IJavaProject javaProject = JavaCore.create(project);
                    if (javaProject.exists()){
                        return javaProject;
                    }
                }
            } catch (CoreException e) {
                DroolsEclipsePlugin.log(e);
            }
        }
        return null;
    }

    protected abstract void createModel(InputStream is);

    public Object getAdapter(@SuppressWarnings("rawtypes") Class type) {
        if (type == IContentOutlinePage.class) {
            return getOverviewOutlinePage();
        }
        if (type == ZoomManager.class) {
            return ((ScalableRootEditPart) getGraphicalViewer()
                    .getRootEditPart()).getZoomManager();
        }
//        if (type == IPropertySheetPage.class) {
//            return new TabbedPropertySheetPage(this);
//        }
        return super.getAdapter(type);
    }

    protected OverviewOutlinePage getOverviewOutlinePage() {
        if (null == overviewOutlinePage && null != getGraphicalViewer()) {
            ScalableRootEditPart rootEditPart = (ScalableRootEditPart) getGraphicalViewer()
                    .getRootEditPart();
            overviewOutlinePage = new OverviewOutlinePage(rootEditPart);
        }
        return overviewOutlinePage;
    }

    public String getContributorId() {
        return getSite().getId();
    }

    /**
     * Writes the content of this editor to the given stream.
     * Possible formats are for example SWT.IMAGE_BMP, IMAGE_GIF,
     * IMAGE_JPEG, IMAGE_PNG.
     * @param stream
     * @param format
     */
    public void createImage(OutputStream stream, int format) {
        SWTGraphics g = null;
        GC gc = null;
        Image image = null;
        LayerManager layerManager = (LayerManager)
            getGraphicalViewer().getEditPartRegistry().get(LayerManager.ID);
        IFigure figure = layerManager.getLayer(LayerConstants.PRINTABLE_LAYERS);
        Rectangle r = figure.getBounds();
        try {
            image = new Image(Display.getDefault(), r.width, r.height);
            gc = new GC(image);
            g = new SWTGraphics(gc);
            g.translate(r.x * -1, r.y * -1);
            figure.paint(g);
            ImageLoader imageLoader = new ImageLoader();
            imageLoader.data = new ImageData[] { image.getImageData() };
            imageLoader.save(stream, format);
        } catch (Throwable t) {
            DroolsEclipsePlugin.log(t);
        } finally {
            if (g != null) {
                g.dispose();
            }
            if (gc != null) {
                gc.dispose();
            }
            if (image != null) {
                image.dispose();
            }
        }
    }
}


/*
 * Copyright 2015 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

package org.eclipse.webdav.internal.kernel.utils;

import java.util.Enumeration;
import java.util.Hashtable;

public class NestedHashtable {

    protected Hashtable localValues = new Hashtable(5);
    protected NestedHashtable defaults = null;

    public NestedHashtable() {
        super();
    }

    /**
     * Constructor for the class. Set the defaults to be
     * the given value.
     *
     * @param defaults the default values for the receiver
     */
    public NestedHashtable(NestedHashtable defaults) {
        super();
        this.defaults = defaults;
    }

    /**
     * Copy all the default values into the receiver.
     */
    public void collapse() {
        if (defaults != null) {
            Enumeration keysEnum = defaults.keys();
            while (keysEnum.hasMoreElements()) {
                Object key = keysEnum.nextElement();
                localValues.put(key, defaults.get(key));
            }
            defaults = null;
        }
    }

    /**
     * Return the value for the given key.
     *
     * @param key the key to look up
     * @return the value for the key or null if none.
     */
    public Object get(Object key) {
        Object value = localValues.get(key);
        if (value == null && defaults != null)
            return defaults.get(key);
        return value;
    }

    /**
     * Return an enumeration over the context's keys. (recursively computes the
     * keys based on keys defaults as well)
     *
     * @return an enumeration over the context keys
     */
    public Enumeration keys() {
        if (defaults == null)
            return localValues.keys();
        return new MergedEnumeration(localValues.keys(), defaults.keys());
    }

    /**
     * Put the given key-value pair into the context.
     *
     * @param key the key
     * @param value its associated value
     */
    public void put(Object key, Object value) {
        localValues.put(key, value);
    }

    /**
     * Remove the given key from the context
     *
     * @param key the key to remove
     */
    public Object remove(Object key) {
        return localValues.remove(key);
    }

    /**
     * Return a string representation of the context.
     *
     * @return the context, as a String
     * @see #toString()
     */
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        Enumeration keysEnum = keys();
        while (keysEnum.hasMoreElements()) {
            Object key = keysEnum.nextElement();
            buffer.append(key.toString());
            buffer.append(": "); //$NON-NLS-1$
            buffer.append(get(key).toString());
            buffer.append('\n');
        }
        return buffer.toString();
    }
}


/*
 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.guvnor.tools.actions;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.webdav.IResponse;
import org.guvnor.tools.Activator;
import org.guvnor.tools.utils.ActionUtils;
import org.guvnor.tools.utils.GuvnorMetadataProps;
import org.guvnor.tools.utils.GuvnorMetadataUtils;
import org.guvnor.tools.utils.PlatformUtils;
import org.guvnor.tools.utils.webdav.IWebDavClient;
import org.guvnor.tools.utils.webdav.ResourceProperties;
import org.guvnor.tools.utils.webdav.WebDavClientFactory;
import org.guvnor.tools.utils.webdav.WebDavException;
import org.guvnor.tools.utils.webdav.WebDavServerCache;

/**
 * Updates a local resource with the latest contents from Guvnor.
 */
public class UpdateAction implements IObjectActionDelegate {

    private IStructuredSelection selectedItems;

    public UpdateAction() {
        super();
    }

    /*
     * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
     */
    public void setActivePart(IAction action, IWorkbenchPart targetPart) { }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
     */
    @SuppressWarnings("unchecked")
    public void run(IAction action) {
        assert(selectedItems != null);
        for (Iterator it = selectedItems.iterator(); it.hasNext();) {
            Object oneItem = it.next();
            if (oneItem instanceof IFile) {
                processUpdate((IFile)oneItem);
            }
        }
        PlatformUtils.updateDecoration();
    }

    private void processUpdate(IFile selectedFile) {
        IResponse response = null;
        try {
            GuvnorMetadataProps props = GuvnorMetadataUtils.getGuvnorMetadata(selectedFile);
            IWebDavClient client = WebDavServerCache.getWebDavClient(props.getRepository());
            if (client == null) {
                client = WebDavClientFactory.createClient(new URL(props.getRepository()));
                WebDavServerCache.cacheWebDavClient(props.getRepository(), client);
            }
            InputStream ins = null;
            try {
                response = client.getResourceInputStream(props.getFullpath());
                ins = response.getInputStream();
            } catch (WebDavException wde) {
                if (wde.getErrorCode() != IResponse.SC_UNAUTHORIZED) {
                    // If not an authentication failure, we don't know what to do with it
                    throw wde;
                }
                boolean retry = PlatformUtils.getInstance().
                                    authenticateForServer(props.getRepository(), client);
                if (retry) {
                    response = client.getResourceInputStream(props.getFullpath());
                    ins = response.getInputStream();
                }
            }
            if (ins != null) {
                selectedFile.setContents(ins, true, true, null);
                GuvnorMetadataUtils.markCurrentGuvnorResource(selectedFile);
                ResourceProperties resProps = client.queryProperties(props.getFullpath());
                GuvnorMetadataProps mdProps = GuvnorMetadataUtils.getGuvnorMetadata(selectedFile);
                mdProps.setVersion(resProps.getLastModifiedDate());
                mdProps.setRevision(resProps.getRevision());
                GuvnorMetadataUtils.setGuvnorMetadataProps(selectedFile.getFullPath(), mdProps);
            }
        } catch (Exception e) {
            Activator.getDefault().displayError(IStatus.ERROR, e.getMessage(), e, true);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ioe) {
                    Activator.getDefault().writeLog(IStatus.ERROR, ioe.getMessage(), ioe);
                }
            }
        }
    }

    private ResourceProperties getRemoteResourceProps(IFile file, GuvnorMetadataProps localProps) {
        ResourceProperties remoteProps = null;
        try {
            IWebDavClient client = WebDavServerCache.getWebDavClient(localProps.getRepository());
            if (client == null) {
                client = WebDavClientFactory.createClient(new URL(localProps.getRepository()));
                WebDavServerCache.cacheWebDavClient(localProps.getRepository(), client);
            }
            try {
                remoteProps = client.queryProperties(localProps.getFullpath());
            } catch (WebDavException wde) {
                if (wde.getErrorCode() != IResponse.SC_UNAUTHORIZED) {
                    // If not an authentication failure, we don't know what to do with it
                    throw wde;
                }
                boolean retry = PlatformUtils.getInstance().
                                    authenticateForServer(localProps.getRepository(), client);
                if (retry) {
                    remoteProps = client.queryProperties(localProps.getFullpath());
                }
            }
        } catch (Exception e) {
            Activator.getDefault().writeLog(IStatus.ERROR, e.getMessage(), e);
        }
        return remoteProps;
    }

    @SuppressWarnings("unchecked")
    private boolean hasChangedRevision(ISelection selection) {
        boolean res = true;
        try {
            if (!(selection instanceof IStructuredSelection)) {
                return false;
            }
            IStructuredSelection sel = (IStructuredSelection)selection;
            for (Iterator<Object> it = sel.iterator(); it.hasNext();) {
                Object oneSelection = it.next();
                if (oneSelection instanceof IFile) {
                    GuvnorMetadataProps localProps =
                        GuvnorMetadataUtils.getGuvnorMetadata((IFile)oneSelection);
                    if (localProps != null) {
                        ResourceProperties remoteProps =
                            getRemoteResourceProps((IFile)oneSelection, localProps);
                        if (remoteProps == null) {
                            res = false;
                            break;
                        }
                        if (remoteProps.getRevision().equals(localProps.getRevision())) {
                            res = false;
                            break;
                        }
                    } else {
                        res = false;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            Activator.getDefault().writeLog(IStatus.ERROR, e.getMessage(), e);
            res = false;
        }
        return res;
    }

    /*
     * @see IActionDelegate#selectionChanged(IAction, ISelection)
     */
    public void selectionChanged(IAction action, ISelection selection) {
        boolean validResourceSet =
            (ActionUtils.checkResourceSet(selection, true) && ActionUtils.areFilesDirty(selection))
            || hasChangedRevision(selection);

        if (validResourceSet) {
            action.setEnabled(true);
            selectedItems = (IStructuredSelection)selection;
        } else {
            action.setEnabled(false);
            selectedItems = null;
        }
    }
}


/*******************************************************************************
 * Copyright (c) 2011, 2012, 2013, 2014 Red Hat, Inc.
 *  All rights reserved.
 * This program is 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:
 * Red Hat, Inc. - initial API and implementation
 *
 ******************************************************************************/

package org.kie.eclipse.server;

import java.util.List;
import java.util.Map;

import org.eclipse.core.resources.IFolder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.wst.server.core.IModule;
import org.eclipse.wst.server.core.IPublishListener;
import org.eclipse.wst.server.core.IRuntime;
import org.eclipse.wst.server.core.IServer;
import org.eclipse.wst.server.core.IServerListener;
import org.eclipse.wst.server.core.IServerType;
import org.eclipse.wst.server.core.IServerWorkingCopy;
import org.eclipse.wst.server.core.ServerPort;

/**
 *
 */
public class ServerProxy implements IServer {

	final IServer server;

	public ServerProxy(IServer server) {
		this.server = server;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getName()
	 */
	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return server.getName();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getId()
	 */
	@Override
	public String getId() {
		// TODO Auto-generated method stub
		return server.getId();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#delete()
	 */
	@Override
	public void delete() throws CoreException {
		server.delete();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#isReadOnly()
	 */
	@Override
	public boolean isReadOnly() {
		return server.isReadOnly();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#isWorkingCopy()
	 */
	@Override
	public boolean isWorkingCopy() {
		// TODO Auto-generated method stub
		return server.isWorkingCopy();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getAdapter(java.lang.Class)
	 */
	@Override
	public Object getAdapter(Class adapter) {
		// TODO Auto-generated method stub
		return server.getAdapter(adapter);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#loadAdapter(java.lang.Class, org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public Object loadAdapter(Class adapter, IProgressMonitor monitor) {
		// TODO Auto-generated method stub
		return server.loadAdapter(adapter, monitor);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getHost()
	 */
	@Override
	public String getHost() {
		// TODO Auto-generated method stub
		return server.getHost();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getRuntime()
	 */
	@Override
	public IRuntime getRuntime() {
		// TODO Auto-generated method stub
		return server.getRuntime();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getServerType()
	 */
	@Override
	public IServerType getServerType() {
		// TODO Auto-generated method stub
		return server.getServerType();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getServerConfiguration()
	 */
	@Override
	public IFolder getServerConfiguration() {
		// TODO Auto-generated method stub
		return server.getServerConfiguration();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#createWorkingCopy()
	 */
	@Override
	public IServerWorkingCopy createWorkingCopy() {
		// TODO Auto-generated method stub
		return server.createWorkingCopy();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getModules()
	 */
	@Override
	public IModule[] getModules() {
		// TODO Auto-generated method stub
		return server.getModules();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#canModifyModules(org.eclipse.wst.server.core.IModule[], org.eclipse.wst.server.core.IModule[], org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public IStatus canModifyModules(IModule[] add, IModule[] remove, IProgressMonitor monitor) {
		// TODO Auto-generated method stub
		return server.canModifyModules(add, remove, monitor);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getAttribute(java.lang.String, int)
	 */
	@Override
	public int getAttribute(String attributeName, int defaultValue) {
		// TODO Auto-generated method stub
		return server.getAttribute(attributeName, defaultValue);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getAttribute(java.lang.String, boolean)
	 */
	@Override
	public boolean getAttribute(String attributeName, boolean defaultValue) {
		// TODO Auto-generated method stub
		return server.getAttribute(attributeName, defaultValue);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getAttribute(java.lang.String, java.lang.String)
	 */
	@Override
	public String getAttribute(String attributeName, String defaultValue) {
		// TODO Auto-generated method stub
		return server.getAttribute(attributeName, defaultValue);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getAttribute(java.lang.String, java.util.List)
	 */
	@Override
	public List<String> getAttribute(String attributeName, List<String> defaultValue) {
		// TODO Auto-generated method stub
		return server.getAttribute(attributeName, defaultValue);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getAttribute(java.lang.String, java.util.Map)
	 */
	@Override
	public Map getAttribute(String attributeName, Map defaultValue) {
		// TODO Auto-generated method stub
		return server.getAttribute(attributeName, defaultValue);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getChildModules(org.eclipse.wst.server.core.IModule[], org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public IModule[] getChildModules(IModule[] module, IProgressMonitor monitor) {
		// TODO Auto-generated method stub
		return server.getChildModules(module, monitor);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getRootModules(org.eclipse.wst.server.core.IModule, org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public IModule[] getRootModules(IModule module, IProgressMonitor monitor) throws CoreException {
		// TODO Auto-generated method stub
		return server.getRootModules(module, monitor);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServerAttributes#getServerPorts(org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public ServerPort[] getServerPorts(IProgressMonitor monitor) {
		// TODO Auto-generated method stub
		return server.getServerPorts(monitor);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.core.runtime.jobs.ISchedulingRule#contains(org.eclipse.core.runtime.jobs.ISchedulingRule)
	 */
	@Override
	public boolean contains(ISchedulingRule rule) {
		// TODO Auto-generated method stub
		return server.contains(rule);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.core.runtime.jobs.ISchedulingRule#isConflicting(org.eclipse.core.runtime.jobs.ISchedulingRule)
	 */
	@Override
	public boolean isConflicting(ISchedulingRule rule) {
		// TODO Auto-generated method stub
		return server.isConflicting(rule);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#getServerState()
	 */
	@Override
	public int getServerState() {
		return IServer.STATE_STARTED;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#getMode()
	 */
	@Override
	public String getMode() {
		// TODO Auto-generated method stub
		return server.getMode();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#getServerPublishState()
	 */
	@Override
	public int getServerPublishState() {
		// TODO Auto-generated method stub
		return server.getServerPublishState();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#addServerListener(org.eclipse.wst.server.core.IServerListener)
	 */
	@Override
	public void addServerListener(IServerListener listener) {
		// TODO Auto-generated method stub
		server.addServerListener(listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#addServerListener(org.eclipse.wst.server.core.IServerListener, int)
	 */
	@Override
	public void addServerListener(IServerListener listener, int eventMask) {
		// TODO Auto-generated method stub
		server.addServerListener(listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#removeServerListener(org.eclipse.wst.server.core.IServerListener)
	 */
	@Override
	public void removeServerListener(IServerListener listener) {
		// TODO Auto-generated method stub
		server.removeServerListener(listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#addPublishListener(org.eclipse.wst.server.core.IPublishListener)
	 */
	@Override
	public void addPublishListener(IPublishListener listener) {
		// TODO Auto-generated method stub
		server.addPublishListener(listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#removePublishListener(org.eclipse.wst.server.core.IPublishListener)
	 */
	@Override
	public void removePublishListener(IPublishListener listener) {
		// TODO Auto-generated method stub
		server.removePublishListener(listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#canPublish()
	 */
	@Override
	public IStatus canPublish() {
		// TODO Auto-generated method stub
		return server.canPublish();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#shouldPublish()
	 */
	@Override
	public boolean shouldPublish() {
		// TODO Auto-generated method stub
		return server.shouldPublish();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#publish(int, org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public IStatus publish(int kind, IProgressMonitor monitor) {
		// TODO Auto-generated method stub
		return server.publish(kind, monitor);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#publish(int, java.util.List, org.eclipse.core.runtime.IAdaptable, org.eclipse.wst.server.core.IServer.IOperationListener)
	 */
	@Override
	public void publish(int kind, List<IModule[]> modules, IAdaptable info, IOperationListener listener) {
		// TODO Auto-generated method stub
		server.publish(kind, modules, info, listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#canStart(java.lang.String)
	 */
	@Override
	public IStatus canStart(String launchMode) {
		// TODO Auto-generated method stub
		return server.canStart(launchMode);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#start(java.lang.String, org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public void start(String launchMode, IProgressMonitor monitor) throws CoreException {
		// TODO Auto-generated method stub
		server.start(launchMode, monitor);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#start(java.lang.String, org.eclipse.wst.server.core.IServer.IOperationListener)
	 */
	@Override
	public void start(String launchMode, IOperationListener listener) {
		// TODO Auto-generated method stub
		server.start(launchMode, listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#canRestart(java.lang.String)
	 */
	@Override
	public IStatus canRestart(String mode) {
		// TODO Auto-generated method stub
		return server.canRestart(mode);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#shouldRestart()
	 */
	@Override
	public boolean shouldRestart() {
		// TODO Auto-generated method stub
		return server.shouldRestart();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#getServerRestartState()
	 */
	@Override
	public boolean getServerRestartState() {
		// TODO Auto-generated method stub
		return server.getServerRestartState();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#restart(java.lang.String, org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public void restart(String launchMode, IProgressMonitor monitor) {
		// TODO Auto-generated method stub
		server.restart(launchMode, monitor);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#restart(java.lang.String, org.eclipse.wst.server.core.IServer.IOperationListener)
	 */
	@Override
	public void restart(String launchMode, IOperationListener listener) {
		// TODO Auto-generated method stub
		server.restart(launchMode, listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#canStop()
	 */
	@Override
	public IStatus canStop() {
		// TODO Auto-generated method stub
		return server.canStop();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#stop(boolean)
	 */
	@Override
	public void stop(boolean force) {
		// TODO Auto-generated method stub
		server.stop(force);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#stop(boolean, org.eclipse.wst.server.core.IServer.IOperationListener)
	 */
	@Override
	public void stop(boolean force, IOperationListener listener) {
		// TODO Auto-generated method stub
		server.stop(force, listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#getModuleState(org.eclipse.wst.server.core.IModule[])
	 */
	@Override
	public int getModuleState(IModule[] module) {
		// TODO Auto-generated method stub
		return server.getModuleState(module);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#getModulePublishState(org.eclipse.wst.server.core.IModule[])
	 */
	@Override
	public int getModulePublishState(IModule[] module) {
		// TODO Auto-generated method stub
		return server.getModulePublishState(module);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#getModuleRestartState(org.eclipse.wst.server.core.IModule[])
	 */
	@Override
	public boolean getModuleRestartState(IModule[] module) {
		// TODO Auto-generated method stub
		return server.getModuleRestartState(module);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#canControlModule(org.eclipse.wst.server.core.IModule[], org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public IStatus canControlModule(IModule[] module, IProgressMonitor monitor) {
		// TODO Auto-generated method stub
		return server.canControlModule(module, monitor);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#canRestartModule(org.eclipse.wst.server.core.IModule[], org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public IStatus canRestartModule(IModule[] module, IProgressMonitor monitor) {
		// TODO Auto-generated method stub
		return server.canRestartModule(module, monitor);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#canPublishModule(org.eclipse.wst.server.core.IModule[], org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public IStatus canPublishModule(IModule[] module, IProgressMonitor monitor) {
		// TODO Auto-generated method stub
		return server.canPublishModule(module, monitor);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#startModule(org.eclipse.wst.server.core.IModule[], org.eclipse.wst.server.core.IServer.IOperationListener)
	 */
	@Override
	public void startModule(IModule[] module, IOperationListener listener) {
		// TODO Auto-generated method stub
		server.startModule(module, listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#stopModule(org.eclipse.wst.server.core.IModule[], org.eclipse.wst.server.core.IServer.IOperationListener)
	 */
	@Override
	public void stopModule(IModule[] module, IOperationListener listener) {
		// TODO Auto-generated method stub
		server.stopModule(module, listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#restartModule(org.eclipse.wst.server.core.IModule[], org.eclipse.wst.server.core.IServer.IOperationListener)
	 */
	@Override
	public void restartModule(IModule[] module, IOperationListener listener) {
		// TODO Auto-generated method stub
		server.restartModule(module, listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#getLaunchConfiguration(boolean, org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public ILaunchConfiguration getLaunchConfiguration(boolean create, IProgressMonitor monitor) throws CoreException {
		// TODO Auto-generated method stub
		return server.getLaunchConfiguration(create, monitor);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#getLaunch()
	 */
	@Override
	public ILaunch getLaunch() {
		// TODO Auto-generated method stub
		return server.getLaunch();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#getStartTimeout()
	 */
	@Override
	public int getStartTimeout() {
		// TODO Auto-generated method stub
		return server.getStartTimeout();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#getStopTimeout()
	 */
	@Override
	public int getStopTimeout() {
		// TODO Auto-generated method stub
		return server.getStopTimeout();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#synchronousStart(java.lang.String, org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public void synchronousStart(String launchMode, IProgressMonitor monitor) throws CoreException {
		// TODO Auto-generated method stub
		server.synchronousStart(launchMode, monitor);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#synchronousStop(boolean)
	 */
	@Override
	public void synchronousStop(boolean force) {
		// TODO Auto-generated method stub
		server.synchronousStop(force);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.wst.server.core.IServer#synchronousRestart(java.lang.String, org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public void synchronousRestart(String launchMode, IProgressMonitor monitor) throws CoreException {
		// TODO Auto-generated method stub
		server.synchronousStart(launchMode, monitor);
	}

}


/*
 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.drools.eclipse.reteoo;

import org.drools.core.base.ClassFieldReader;
import org.drools.core.rule.constraint.MvelConstraint;
import org.drools.core.spi.AlphaNodeFieldConstraint;
import org.drools.core.spi.Constraint;
import org.drools.core.spi.FieldValue;
import org.drools.core.spi.InternalReadAccessor;
import org.drools.core.reteoo.AlphaNode;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.swt.graphics.Color;

/**
 * Wraps {@link org.drools.core.reteoo.AlphaNode} and adds visual extras like color information
 */
public class AlphaNodeVertex extends BaseVertex {

    private final AlphaNode node;

    private final String    NODE_NAME = "AlphaNode";

    /**
     * Constructor
     *
     * @param node node to be wrapped
     */
    public AlphaNodeVertex(final AlphaNode node) {
        super();
        this.node = node;
    }

    /* (non-Javadoc)
     * @see org.drools.core.reteoo.BaseNodeVertex#getHtml()
     */
    public String getHtml() {
        AlphaNodeFieldConstraint constraint = this.node.getConstraint();
        if (constraint instanceof MvelConstraint) {
        	MvelConstraint mvelConstraint = (MvelConstraint) constraint;
            return NODE_NAME + "
expression : " + mvelConstraint.toString();
        }
        return NODE_NAME + "
";
    }

    /* (non-Javadoc)
     * @see org.drools.eclipse.editors.rete.model.BaseVertex#toString()
     */
    public String toString() {
        return this.node.toString();
    }

    /* (non-Javadoc)
     * @see org.drools.core.reteoo.BaseNodeVertex#getFillColor()
     */
    public Color getFillColor() {
        return ColorConstants.blue;
    }

    /**
     * Constraint has field extractor and this method is returning fieldName
     * it.
     *
     * @return field name
     */
    public String getFieldName() {
        AlphaNodeFieldConstraint constraint = this.node.getConstraint();
        if (constraint instanceof MvelConstraint) {
        	MvelConstraint mvelConstraint = (MvelConstraint) constraint;
            InternalReadAccessor accessor = mvelConstraint.getFieldExtractor();
            if (accessor instanceof ClassFieldReader) {
                return ((ClassFieldReader) accessor).getFieldName();
            }
        }
        return null;
    }

    /**
     * Constraint's evaluator string
     *
     * @return evaluator string
     */
    public String getEvaluator() {
        AlphaNodeFieldConstraint constraint = this.node.getConstraint();
        if (constraint instanceof MvelConstraint) {
        	MvelConstraint mvelConstraint = (MvelConstraint) constraint;
            return mvelConstraint.toString();
        }
        return null;
    }

    /**
     * Constraint field string
     *
     * @return field string
     */
    public String getValue() {
        AlphaNodeFieldConstraint constraint = this.node.getConstraint();
        if (constraint instanceof MvelConstraint) {
        	MvelConstraint mvelConstraint = (MvelConstraint) constraint;
        	FieldValue field = mvelConstraint.getField();
            return field != null ? field.toString() : null;
        }
        return null;
    }

    /**
     * Constraint
     *
     * @return constraint
     */
    public Constraint getConstraint() {
        return this.node.getConstraint();
    }

}


/*
 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.guvnor.tools.actions;

import java.util.Iterator;

import org.eclipse.core.resources.IFile;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.guvnor.tools.utils.ActionUtils;
import org.guvnor.tools.utils.GuvnorMetadataUtils;
import org.guvnor.tools.utils.PlatformUtils;

/**
 * Commits changes to Guvnor resources.
 */
public class CommitAction implements IObjectActionDelegate {

    private IStructuredSelection selectedItems;

    public CommitAction() {
        super();
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction, org.eclipse.ui.IWorkbenchPart)
     */
    public void setActivePart(IAction action, IWorkbenchPart targetPart) { }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
     */
    @SuppressWarnings("unchecked")
    public void run(IAction action) {
        assert(selectedItems != null);
        for (Iterator it = selectedItems.iterator(); it.hasNext();) {
            Object oneSelection = it.next();
            if (oneSelection instanceof IFile) {
                GuvnorMetadataUtils.commitFileChanges((IFile)oneSelection);
            }
        }
        PlatformUtils.updateDecoration();
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
     */
    public void selectionChanged(IAction action, ISelection selection) {
        boolean validResourceSet = ActionUtils.checkResourceSet(selection, true)
                                   && ActionUtils.areFilesDirty(selection);
        if (validResourceSet) {
            action.setEnabled(true);
            selectedItems = (IStructuredSelection)selection;
        } else {
            action.setEnabled(false);
            selectedItems = null;
        }
    }
}