/*******************************************************************************
 * Copyright (c) 2000, 2004 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.help.ui.internal.search;
import org.eclipse.core.runtime.*;
import org.eclipse.help.internal.base.*;
import org.eclipse.help.ui.internal.ide.*;
import org.eclipse.jface.dialogs.*;
import org.eclipse.jface.window.*;
import org.eclipse.search.ui.*;
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.*;
import org.eclipse.ui.dialogs.*;
import org.eclipse.ui.help.*;
/**
 * HelpSearchPage
 */
public class HelpSearchPage extends DialogPage implements ISearchPage {
	protected Combo searchWordCombo = null;
	protected static java.util.List previousSearchQueryData = new java.util.ArrayList(
			20);
	protected Button all;
	protected Button selected;
	protected Text selectedWorkingSetsText;
	//private Button headingsButton = null;
	private ISearchPageContainer scontainer = null;
	private boolean firstTime = true;
	// Search query based on the data entered in the UI
	protected SearchQueryData searchQueryData;
	protected Button includeDisabledActivities;
	/**
	 * Search Page
	 */
	public HelpSearchPage() {
		super();
		searchQueryData = new SearchQueryData();
	}
	public void createControl(Composite parent) {
		Composite control = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		layout.numColumns = 2;
		control.setLayout(layout);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		control.setLayoutData(gd);
		// Search Expression
		Label expressionLabel = new Label(control, SWT.LEFT);
		expressionLabel.setText(HelpIdeResources.getString("expression")); //$NON-NLS-1$
		// Pattern combo
		searchWordCombo = new Combo(control, SWT.SINGLE | SWT.BORDER);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.widthHint = convertWidthInCharsToPixels(30);
		searchWordCombo.setLayoutData(gd);
		// Not done here to prevent page from resizing
		// fPattern.setItems(getPreviousSearchPatterns());
		searchWordCombo.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				if (searchWordCombo.getSelectionIndex() < 0)
					return;
				int index = previousSearchQueryData.size() - 1
						- searchWordCombo.getSelectionIndex();
				searchQueryData = (SearchQueryData) previousSearchQueryData
						.get(index);
				searchWordCombo.setText(searchQueryData.getSearchWord());
				all.setSelection(!searchQueryData.isBookFiltering());
				selected.setSelection(searchQueryData.isBookFiltering());
				includeDisabledActivities.setSelection(!searchQueryData
						.isActivityFiltering());
				displaySelectedBooks();
				//headingsButton.setSelection(searchOperation.getQueryData().isFieldsSearch());
			}
		});
		searchWordCombo.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				updateSearchButtonState();
			}
		});
		// Space
		new Label(control, SWT.NONE);
		// Syntax description
		Label label = new Label(control, SWT.LEFT);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 1;
		label.setLayoutData(gd);
		label.setText(HelpIdeResources.getString("expression_label")); //$NON-NLS-1$
		// Headings only button
		//		headingsButton = new Button(control, SWT.CHECK);
		//		gd = new GridData();
		//		gd.horizontalAlignment = gd.BEGINNING;
		//		gd = new GridData();
		//		gd.verticalAlignment = gd.VERTICAL_ALIGN_BEGINNING;
		//		headingsButton.setLayoutData(gd);
		//      headingsButton.setFont(font);
		//		headingsButton.setText(WorkbenchResources.getString("Search_headers_only"));
		// Filtering group
		Group filteringGroup = new Group(control, SWT.NONE);
		filteringGroup.setLayout(layout);
		gd = new GridData(GridData.FILL_BOTH);
		gd.horizontalSpan = 2;
		gd.grabExcessHorizontalSpace = true;
		gd.grabExcessVerticalSpace = true;
		filteringGroup.setLayoutData(gd);
		filteringGroup.setText(HelpIdeResources.getString("limit_to")); //$NON-NLS-1$
		layout = new GridLayout();
		layout.numColumns = 3;
		filteringGroup.setLayout(layout);
		//
		all = new Button(filteringGroup, SWT.RADIO);
		all.setSelection(!searchQueryData.isBookFiltering());
		all.setText(HelpIdeResources.getString("HelpSearchPage.allBooks")); //$NON-NLS-1$
		gd = new GridData();
		gd.horizontalSpan = 3;
		all.setLayoutData(gd);
		all.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				searchQueryData.setBookFiltering(false);
			}
		});
		//
		selected = new Button(filteringGroup, SWT.RADIO);
		selected.setSelection(searchQueryData.isBookFiltering());
		selected.setText(HelpIdeResources
				.getString("HelpSearchPage.selectedBooks")); //$NON-NLS-1$
		selected.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				searchQueryData.setBookFiltering(true);
				updateSearchButtonState();
			}
		});
		//
		selectedWorkingSetsText = new Text(filteringGroup, SWT.SINGLE
				| SWT.BORDER | SWT.READ_ONLY);
		displaySelectedBooks();
		//
		Button chooseWorkingSet = new Button(filteringGroup, SWT.PUSH);
		org.eclipse.jface.dialogs.Dialog.applyDialogFont(chooseWorkingSet);
		setButtonLayoutData(chooseWorkingSet);
		chooseWorkingSet.setText(HelpIdeResources
				.getString("HelpSearchPage.choose")); //$NON-NLS-1$
		SWTUtil.setButtonDimensionHint(chooseWorkingSet);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalIndent = 8;
		gd.widthHint = SWTUtil.convertWidthInCharsToPixels(30,
				selectedWorkingSetsText);
		selectedWorkingSetsText.setLayoutData(gd);
		chooseWorkingSet.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				IWorkingSetSelectionDialog dialog = PlatformUI.getWorkbench()
						.getWorkingSetManager()
						.createWorkingSetSelectionDialog(selected.getShell(),
								false);
				// no multiple selection
				if (dialog.open() == Window.OK) {
					all.setSelection(false);
					selected.setSelection(true);
					searchQueryData.setBookFiltering(true);
					searchQueryData.setSelectedWorkingSets(dialog
							.getSelection());
					displaySelectedBooks();
				}
			}
		});
		includeDisabledActivities = new Button(filteringGroup, SWT.CHECK);
		gd = new GridData();
		gd.horizontalSpan = 3;
		includeDisabledActivities.setLayoutData(gd);
		includeDisabledActivities.setText(HelpIdeResources
				.getString("searchDisabledActivities")); //$NON-NLS-1$
		includeDisabledActivities.addSelectionListener(new SelectionListener() {
			public void widgetSelected(SelectionEvent e) {
				searchQueryData.setActivityFiltering(!includeDisabledActivities
						.getSelection());
			}
			public void widgetDefaultSelected(SelectionEvent e) {
				widgetSelected(e);
			}
		});
		org.eclipse.jface.dialogs.Dialog.applyDialogFont(control);
		setControl(control);
		WorkbenchHelp.setHelp(control, IHelpIdeConstants.SEARCH_PAGE);
	}
	/**
	 * @see ISearchPage#performAction()
	 */
	public boolean performAction() {
		searchQueryData.setSearchWord(searchWordCombo.getText());
		searchQueryData.setFieldsSearch(false);
		// Save working set
		Preferences prefs = HelpBasePlugin.getDefault().getPluginPreferences();
		String lastWS = prefs.getString(BaseHelpSystem.WORKING_SET);
		IWorkingSet[] iws = searchQueryData.getSelectedWorkingSets();
		if (searchQueryData.isBookFiltering() && iws != null && iws.length > 0
				&& !iws[0].getName().equals(lastWS)) {
			prefs.setValue(BaseHelpSystem.WORKING_SET, iws[0].getName());
			HelpBasePlugin.getDefault().savePluginPreferences();
		} else if (!searchQueryData.isBookFiltering()
				&& (lastWS != null || lastWS.length() > 0)) {
			prefs.setValue(BaseHelpSystem.WORKING_SET, ""); //$NON-NLS-1$
			HelpBasePlugin.getDefault().savePluginPreferences();
		}
		if (!previousSearchQueryData.contains(searchQueryData))
			previousSearchQueryData.add(searchQueryData);
		//
		ISearchQuery searchUIQuery = new HelpSearchQuery(searchQueryData);
		NewSearchUI.activateSearchResultView();
		NewSearchUI.runQuery(searchUIQuery);
		return true;
	}
	public void setContainer(ISearchPageContainer container) {
		scontainer = container;
	}
	/*
	 * Implements method from IDialogPage
	 */
	public void setVisible(boolean visible) {
		if (visible && searchWordCombo != null) {
			if (firstTime) {
				firstTime = false;
				// Set item and text here to prevent page from resizing
				String[] patterns = new String[previousSearchQueryData.size()];
				for (int i = 0; i < previousSearchQueryData.size(); i++) {
					patterns[previousSearchQueryData.size() - 1 - i] = ((SearchQueryData) previousSearchQueryData
							.get(i)).getSearchWord();
				}
				searchWordCombo.setItems(patterns);
			}
			searchWordCombo.setFocus();
			updateSearchButtonState();
		}
		super.setVisible(visible);
	}
	/**
	 * Lists selected books in the selection field. If filtering dissabled or
	 * all books are selected, it will display "All"
	 */
	protected void displaySelectedBooks() {
		String workingSetNames = ""; //$NON-NLS-1$
		if (searchQueryData.isBookFiltering()) {
			IWorkingSet[] workingSets = searchQueryData
					.getSelectedWorkingSets();
			for (int i = 0; i < workingSets.length; i++) {
				String workingSet = workingSets[i].getName();
				if (workingSetNames.length() <= 0)
					workingSetNames = workingSet;
				else
					workingSetNames += HelpIdeResources
							.getString("HelpSearchPage.bookLabelSeparator") //$NON-NLS-1$
							+ workingSet;
			}
		} else {
			workingSetNames = ""; //$NON-NLS-1$
		}
		selectedWorkingSetsText.setText(workingSetNames);
		updateSearchButtonState();
	}
	protected void updateSearchButtonState() {
		boolean searchWordValid = searchWordCombo.getText() != null
				&& searchWordCombo.getText().trim().length() > 0;
		boolean workingSetValid = selectedWorkingSetsText.getText() != null
				&& selectedWorkingSetsText.getText().length() > 0;
		scontainer.setPerformActionEnabled(searchWordValid
				&& (all.getSelection() || workingSetValid));
	}
}