package com.quantum.editors;

import com.quantum.QuantumPlugin;

import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.editors.text.TextEditor;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;

public class SQLEditor extends TextEditor {
	private SQLSourceViewerConfiguration config;
	private ColorManager colorManager;
	private SQLContentOutlinePage outlinePage;
	/**
	 * An editor capable of editing SQL scripts
	 */
	public SQLEditor() {
		super();
//System.out.println("SQL Editor");
		colorManager = new ColorManager();
		config = new SQLSourceViewerConfiguration(colorManager);
		config.loadPrefs();
		
		setPreferenceStore(QuantumPlugin.getDefault().getPreferenceStore());
		IPropertyChangeListener preferenceListener = new IPropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent event) {
				config.loadPrefs();
				config.initializeColors();
				getSourceViewer().invalidateTextPresentation();
				StyledText widget = getSourceViewer().getTextWidget();
				FontData font = PreferenceConverter.getFontData(getPreferenceStore(), "quantum.font"); //$NON-NLS-1$
				widget.setFont(new Font(Display.getCurrent(), font));
				Color background = colorManager.getColor(SQLColorConstants.BACKGROUND);
				widget.setBackground(background);
			}
		};
		getPreferenceStore().
			addPropertyChangeListener(preferenceListener);

		setSourceViewerConfiguration(config);
		setDocumentProvider(new SQLDocumentProvider());
	}
	public void dispose() {
		colorManager.dispose();
		super.dispose();
	}
	public void createPartControl(Composite arg0) {
		super.createPartControl(arg0);
		StyledText widget = getSourceViewer().getTextWidget();
		FontData font = PreferenceConverter.getFontData(getPreferenceStore(), "quantum.font"); //$NON-NLS-1$
		widget.setFont(new Font(Display.getCurrent(), font));
		Color background = colorManager.getColor(SQLColorConstants.BACKGROUND);
		widget.setBackground(background);
	}
	
	public Object getAdapter(Class required) {
		if (IContentOutlinePage.class.equals(required)) {
			if (this.outlinePage == null) {
				this.outlinePage= new SQLContentOutlinePage(
						(SQLDocumentProvider) getDocumentProvider(), this);
				if (getEditorInput() != null)
					this.outlinePage.setInput(getEditorInput());
			}
			return this.outlinePage;
		}
		return super.getAdapter(required);
	}

}