/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You 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 poi.support;

import java.io.IOException;
import java.io.OutputStream;

public class POIFormatter implements Closeable, Flushable {

	private StringBuffer sb;
	private OutputStream os;
	private boolean hasClosed;
	private IOException ioException;

	public POIFormatter(StringBuffer sb) {
		this.os = null;
		this.sb = sb;
		this.hasClosed = false;
		this.ioException = null;
	}

	public POIFormatter(OutputStream os) {
		this.os = os;
		this.sb = new StringBuffer();
		this.hasClosed = false;
		this.ioException = null;
	}

	public void format(String fmt, Object[] parts) {
		if (null != os) {
			StringBuffer s = new StringBuffer();
			POIFormatterUtil.format(s, fmt, parts);
			try {
				os.write(new String(s).getBytes());
			} catch (IOException e) {
				ioException = e;
				e.printStackTrace();
			}
		} else {
			POIFormatterUtil.format(sb, fmt, parts);
		}
	}

	public void format(String fmt) {
		this.format(fmt, null);
	}

	public String toString() {
		if (null != os) {
			return os.toString();
		} else {
			return new String(sb);
		}
	}

	public void flush() {
		try {
			os.flush();
		} catch (IOException e) {
			ioException = e;
			e.printStackTrace();
		}
	}

	public void close() {
		if (hasClosed) {
			throw new RuntimeException("FormatterClosedException");
		} else {
			hasClosed = true;
		}
		try {
			os.close();
		} catch (IOException e) {
			ioException = e;
			e.printStackTrace();
		}
	}

	public IOException ioException() {
		return ioException;
	}
}
