package net.noderunner.amazon.s3.emulator;

import java.util.Date;
import java.util.Stack;

import net.noderunner.amazon.s3.ISO801DateFormat;

/**
 * Outputs XML. Not thread safe.
 * 
 * @author Elias Ross
 */
public class Writer {

	private Stack<String> tags = new Stack<String>();
	
	private StringBuilder sb = new StringBuilder();
	
	/**
	 * Starts an XML tag.
	 */
	public Writer start(String tag) {
		sb.append("<").append(tag).append(">");
		tags.push(tag);
		return this;
	}
	
	/**
	 * Ends an XML tag.
	 */
	public Writer end() {
		String tag = tags.pop();
		sb.append("</").append(tag).append(">");
		return this;
	}
	
	/**
	 * Writes character data.
	 */
	public Writer write(String s) {
		s = s.replaceAll("&", "&amp;");
		s = s.replaceAll("<", "&lt;");
		sb.append(s);
		return this;
	}
	
	/**
	 * Writes to a writer.
	 */
	public Writer write(Writer w) {
		sb.append(w.toString());
		return this;
	}
	
	/**
	 * Converts to a string.
	 */
	@Override
	public String toString() {
		return sb.toString();
	}

	/**
	 * Writes an ISO801 date.
	 */
	public Writer write(Date lastModified) {
		return write(new ISO801DateFormat().format(lastModified));
	}

	/**
	 * Writes a Long value.
	 */
	public Writer write(long size) {
		return write(String.valueOf(size));
	}
	
}
