/* $Id: ScriptEditorDocumentProvider.java,v 1.2 2005/11/20 17:34:34 dougsatch Exp $ */
package com.something.eclipse.script.editors;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IPathEditorInput;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.editors.text.FileDocumentProvider;

/**
 * 
 * @author Doug Satchwell
 * @version $Id: ScriptEditorDocumentProvider.java,v 1.2 2005/11/20 17:34:34 dougsatch Exp $
 */
public class ScriptEditorDocumentProvider extends FileDocumentProvider
{
	protected IDocument createDocument(Object element) throws CoreException
	{
		IDocument document = null;
		// For some reason, when opening and external file a JavaFileEditorInput is returned!
		if (element instanceof IPathEditorInput)
		{
			IPathEditorInput i = (IPathEditorInput) element;
			document = createEmptyDocument();
			if (setDocumentContentJava(document, i, getEncoding(element)))
			{
				setupDocument(element, document);
			}
		}
		else
		{
			document = super.createDocument(element);
		}
		return document;
	}

	protected boolean setDocumentContentJava(IDocument document, IPathEditorInput editorInput, String encoding) throws CoreException
	{

		IPath path = editorInput.getPath();
		File file = path.toFile();
		InputStream contentStream = null;
		try
		{
			contentStream = new BufferedInputStream(new FileInputStream(file));
			setDocumentContent(document, contentStream, encoding);
		}
		catch (IOException ex)
		{
			String message = (ex.getMessage() != null ? ex.getMessage() : ""); //$NON-NLS-1$
			IStatus s = new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, IStatus.OK, message, ex);
			throw new CoreException(s);
		}
		finally
		{
			try
			{
				contentStream.close();
			}
			catch (IOException e1)
			{
			}
		}
		return true;
	}

}