/**
 * Copyright (c) 2003-2005, www.pdfbox.org
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. Neither the name of pdfbox; nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * http://www.pdfbox.org
 *
 */
package org.pdfbox.pdfwriter;

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import java.text.DecimalFormat;
import java.text.NumberFormat;

import org.pdfbox.persistence.util.COSObjectKey;

import org.pdfbox.cos.COSBase;
import org.pdfbox.cos.COSFloat;
import org.pdfbox.cos.COSName;
import org.pdfbox.cos.COSString;
import org.pdfbox.cos.COSBoolean;
import org.pdfbox.cos.COSArray;
import org.pdfbox.cos.COSDocument;
import org.pdfbox.cos.COSStream;
import org.pdfbox.cos.COSObject;
import org.pdfbox.cos.COSInteger;
import org.pdfbox.cos.COSNull;

import org.apache.log4j.Logger;

/**
 * subclass of COSWriterAbstract to write xml instead of binary pdf.
 * 
 * @author Mark D. Anderson (mda@discerning.com)
 * @version $ Revision: 1.32 $
 */
public class COSWriterXML extends COSWriterAbstract
{

    private static Logger log = Logger.getLogger( COSWriterXML.class );

    /**
     * COSWriterXML constructor comment.
     *
     * @param os The wrapped output stream.
     */
    public COSWriterXML(OutputStream os)
    {
        super(os);
    }

    private int nesting = 0;

    private String base_name(COSBase obj)
    {
	String s = obj.getClass().getName();
	int ind = s.lastIndexOf(".COS");
	return ind > 0 ? s.substring(ind + 4) : s;
    }

    private void write(byte[] b) throws IOException {
	getOutput().write(b);
    }
    private void write(byte[] b, int off, int len) throws IOException {
	getOutput().write(b, off, len);
    }
    private void write(String s) throws IOException {
	getOutput().write(s.getBytes());
    }

    private void indent() throws IOException {
	for(int i=0;i<nesting;++i) {write(" ");}
    }

    private void startTag(String tagname) throws IOException {
	startTag(tagname, true, true);
    }

    private void startTag(String tagname, boolean pre_indent, boolean post_eol) throws IOException {
	if (pre_indent) indent();
	write("<" + tagname + (post_eol ? ">\n" : ">"));
	nesting++;
    }

    private void startTag(String tagname, String atts, boolean pre_indent, boolean post_eol) throws IOException {
	startTag(tagname + " " + atts, pre_indent, post_eol);
    }

    private void endTag(String tagname) throws IOException {endTag(tagname, true, true);}

    private void endTag(String tagname, boolean pre_indent, boolean post_eol) throws IOException {
	nesting--;
	if (pre_indent) {write("\n"); indent();}
	write("</" + tagname + (post_eol ? ">\n" : ">"));
    }

    private void basic(String tagname, byte[] contents) throws IOException {
	startTag(tagname, false, false);
	write(contents);
	endTag(tagname, false, false);
    }
    private void basic(String tagname, String contents) throws IOException {
	basic(tagname, contents.getBytes());
    }
    private void selfClosing(String tagname, String atts) throws IOException {
	indent();
	write("<" + tagname + (atts != null && atts.length() > 0 ? " " + atts : "") + "/>\n"); 
    }

    // not much point in retaining this
    public long getCurrentXRefPos()
    {
	return -1;
    }
    public void objectStart( COSBase obj, COSObjectKey currentObjectKey ) throws IOException
    {
	startTag(base_name(obj),
		 "key='" + currentObjectKey.getNumber() + "' gen='" + currentObjectKey.getGeneration() + "'",
		 true, true);
    }
    public void objectEnd( COSBase obj) throws IOException
    {
	endTag(base_name(obj));
    }
    public void objectWrite(COSString obj) throws IOException
    {
	basic("string", obj.getBytes());
    }
    public void objectWrite(COSBoolean obj) throws IOException
    {
	basic("boolean", obj.getValue() ? "true" : "false");
    }
    public void objectWrite(COSFloat obj) throws IOException
    {
	basic("float", "" + obj.floatValue());
    }
    public void objectWrite(COSInteger obj) throws IOException
    {
	basic("integer", "" + obj.longValue());
    }
    // used if the value in a dictionary happens to be a name
    public void objectWrite(COSName obj) throws IOException
    {
	basic("name", obj.getName());
    }
    public void objectWrite(COSNull obj) throws IOException
    {
	// do nothing
    }
    public void documentStart(COSDocument doc) throws IOException
    {
	startTag("document");
    }
    public void documentEnd() throws IOException
    {
	endTag("document");
    }
    public void bodyStart() throws IOException
    {
	startTag("body");
    }
    public void bodyEnd() throws IOException
    {
	endTag("body");
    }
    public void writeHeader(COSDocument doc) throws IOException
    {
	startTag("header"); 
	write(doc.getHeaderString());
	endTag("header");
    }

    public void trailerStart() throws IOException 
    {
	startTag("trailer");
    }
    public void trailerEnd(long startXref) throws IOException
    {
	// ignore startXref
	endTag("trailer");
    }
    public void xrefStart(long lastKeyNumber) throws IOException
    {
	// ignore key number
	String s = "<xref lastkey='" + lastKeyNumber + "'>";
	write(s.getBytes());	
    }
    public void xrefEntryFree() throws IOException
    {
	selfClosing("xrefempty", "");
    }
    public void xrefEntry(COSWriterXRefEntry entry) throws IOException
    {
	selfClosing("xrefentry", "offset='" + entry.getOffset() + 
		     "' gen='" + entry.getKey().getGeneration() + "' free='" + entry.isFree() + "'");
    }
    public void xrefEnd() throws IOException
    {
	endTag("xref");
    }
    public void arrayStart(COSArray obj) throws IOException
    {
	startTag("array");
    }
    public void arrayElementStart(int count) throws IOException
    {
    }
    public void arrayElementEnd(boolean hasNext, int count) throws IOException
    {
	write("\n");
    }
    public void arrayEnd() throws IOException
    {
	endTag("array");
    }
    public void dictStart() throws IOException
    {
	startTag("dict");
    }
    public void dictName(COSName name) throws IOException
    {
	startTag("dictentry", "name='" + name.getName() + "'", true, false);
	//write("\n");
    }
    public void dictPairEnd() throws IOException
    {
	endTag("dictentry", false, true);
    }
    public void dictEnd() throws IOException
    {
	endTag("dict");
    }
    public void writeRefKey(COSObjectKey key) throws IOException
    {
	String s= "<ref key='" + key.getNumber() + "' gen='" + key.getGeneration() + "'/>";
	write(s);
    }
    public void streamStart() throws IOException
    {
	startTag("stream");
    }
    public void streamBlock(byte[] buffer, int amountRead) throws IOException
    {
	write(buffer, 0, amountRead);
    }
    public void streamEnd() throws IOException
    {
	endTag("stream");
    }
}
