/*
 * @(#)DocumentWriter.java  1.0  1999-10-19
 *
 * Copyright (c) 1999 Werner Randelshofer, Immensee, Switzerland.
 * All rights reserved.
 *
 * You may not use, copy or modify this file, except in compliance with the
 * license agreement you entered into with Werner Randelshofer.
 * For details see accompanying license terms.
 */
package ch.randelshofer.io;

import java.io.*;
import javax.swing.text.*;

/**
 * This class implements a writer in which the data is written
 * into a document.
 *
 * @version     1.0 1999-10-19
 * @author      Werner Randelshofer
 */
public class DocumentWriter
extends Writer {

  /** The document. */
  private Document doc;

  /**
   * Flag indicating whether the stream has been closed.
   */
      private boolean isClosed = false;

  public DocumentWriter(Document doc) {
    this.doc = doc;
  }

  /** Check to make sure that the stream has not been closed */
  private void ensureOpen()
  throws IOException {
    if (isClosed) {
      throw new IOException("Stream closed.");
    }
  }

  public void close() {
    if (isClosed == false) {
      flush();
      isClosed = true;
    }
  }

  public void flush() {
  }

  public void write(char cbuf)
  throws IOException {
    ensureOpen();
    write( new char[] {cbuf}, 0, 1);
  }

  public void write(int b)
  throws IOException {
    ensureOpen();
    write( new char[] {(char) b}, 0, 1);
  }

  public void write(char cbuf[], int off, int len)
  throws IOException {
    ensureOpen();
    try {
      doc.insertString(doc.getLength(), new String(cbuf, off, len), null);
      } 
    catch (BadLocationException ble) {
      throw new IOException(ble.getMessage());
    }
  }

  public void write(String str)
  throws IOException {
    ensureOpen();
    try {
      doc.insertString(doc.getLength(), str, null);
      } 
    catch (BadLocationException ble) {
      throw new IOException(ble.getMessage());
    }
  }

  public void write(String str, int off, int len)
  throws IOException {
    ensureOpen();
    try {
      doc.insertString(doc.getLength(), str.substring(off,len), null);
      } 
    catch (BadLocationException ble) {
      throw new IOException(ble.getMessage());
    }
  }
}
