/*
 * Copyright 2006 Mask@ Project.
 * 
 * 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.maskat.ide.editors;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.gef.editparts.AbstractGraphicalEditPart;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.text.FindReplaceDocumentAdapter;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.ui.texteditor.DocumentProviderRegistry;
import org.maskat.framework.screendef.IComponentDef;
import org.maskat.ide.MaskatIDEPlugin;

public class MaskatTextEditor extends AbstractTextEditor implements ISelectionListener {

	public void init(IEditorSite site, IEditorInput input) throws PartInitException {
		PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService()
				.addSelectionListener(this);
		super.init(site, input);
	}

	public void dispose() {
		PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService()
				.removeSelectionListener(this);
		super.dispose();
	}

	private String lastRevealedName = null;

	public void selectionChanged(IWorkbenchPart part, ISelection selection) {
		if (selection instanceof StructuredSelection) {
			StructuredSelection ss = (StructuredSelection) selection;
			if (ss.getFirstElement() instanceof AbstractGraphicalEditPart) {
				AbstractGraphicalEditPart ssG = (AbstractGraphicalEditPart) ss
						.getFirstElement();
				Object model = ssG.getModel();
				if (model instanceof IComponentDef) {
					try {
						String name = ((IComponentDef) model).getName();
						if (name.equals(lastRevealedName)) {
							return;
						}
						lastRevealedName = name;
						//
						// String content = this.getDocumentProvider()
						// .getDocument(this.getEditorInput()).get();
						//
						// XMLInputFactory factory =
						// XMLInputFactory.newInstance();
						//
						// XMLStreamReader reader = factory
						// .createXMLStreamReader(new StringReader(content));
						//
						// while (reader.hasNext()) {
						// int eventType = reader.next();
						// if (eventType == XMLStreamConstants.START_ELEMENT) {
						// // element
						// // nameのチェックがあれば、もっと厳密
						// if (name.equals(reader.getAttributeValue(null,
						// "name"))) {
						// this.selectAndReveal(reader.getLocation()
						// .getCharacterOffset() - 1, 1);
						// }
						// }
						// }

						// 文字列の検索
						IDocument doc = this.getDocumentProvider().getDocument(
								this.getEditorInput());

						FindReplaceDocumentAdapter finder = new FindReplaceDocumentAdapter(
								doc);
						if (finder.length() == 0) {
							// In case that find will throw BadLocationException
							return;
						}
						IRegion region = finder.find(0, name, true, true, true, false);
						if (region != null)
							this.selectAndReveal(region.getOffset(), region.getLength());
					} catch (Exception e) {
						IStatus status = new Status(IStatus.ERROR, // ステータス種別:エラー
								MaskatIDEPlugin.PLUGIN_ID, // プラグインID
								0, // エラーコード
								e.getMessage() == null ? "" : e.getMessage(), // エラーメッセージ
								e); // 例外オブジェクト
						ErrorDialog.openError(this.getSite().getShell(), "コンポーネント検索", // タイトル
								"コンポーネント検索処理に失敗しました。", // エラーメッセージ
								status);
					}
				}
			}
		}
	}

	protected void setDocumentProvider(IEditorInput input) {
		super.setDocumentProvider(DocumentProviderRegistry.getDefault()
				.getDocumentProvider(input));
	}
}
