/**
 * 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.COSDictionary;
import org.pdfbox.cos.COSInteger;
import org.pdfbox.cos.COSNull;

import org.apache.log4j.Logger;

/**
 * Writes out PDF (implements COSWriterAbstract, driven by COSWriterVisitor) 
 *
 * @author Michael Traut
 * @author Ben Litchfield (ben@benlitchfield.com)
 * @version $Revision: 1.32 $
 */
public class COSWriterPDF extends COSWriterAbstract
{

    private static Logger log = Logger.getLogger( COSWriterPDF.class );
    /**
     * The dictionary open token.
     */
    public static final byte[] DICT_OPEN = "<<".getBytes();
    /**
     * The dictionary close token.
     */
    public static final byte[] DICT_CLOSE = ">>".getBytes();
    /**
     * space character.
     */
    public static final byte[] SPACE = " ".getBytes();
    /**
     * The start to a PDF comment.
     */
    public static final byte[] COMMENT = "%".getBytes();

    /**
     * The output version of the PDF.
     */
    public static final byte[] VERSION = "PDF-1.4".getBytes();
    /**
     * Garbage bytes used to create the PDF header.
     */
    public static final byte[] GARBAGE = new byte[] {(byte)0xf6, (byte)0xe4, (byte)0xfc, (byte)0xdf};
    /**
     * The EOF constant.
     */
    public static final byte[] EOF = "%%EOF".getBytes();
    // pdf tokens

    /**
     * The reference token.
     */
    public static final byte[] REFERENCE = "R".getBytes();
    /**
     * The XREF token.
     */
    public static final byte[] XREF = "xref".getBytes();
    /**
     * The xref free token.
     */
    public static final byte[] XREF_FREE = "f".getBytes();
    /**
     * The xref used token.
     */
    public static final byte[] XREF_USED = "n".getBytes();
    /**
     * The trailer token.
     */
    public static final byte[] TRAILER = "trailer".getBytes();
    /**
     * The start xref token.
     */
    public static final byte[] STARTXREF = "startxref".getBytes();
    /**
     * The starting object token.
     */
    public static final byte[] OBJ = "obj".getBytes();
    /**
     * The end object token.
     */
    public static final byte[] ENDOBJ = "endobj".getBytes();
    /**
     * The array open token.
     */
    public static final byte[] ARRAY_OPEN = "[".getBytes();
    /**
     * The array close token.
     */
    public static final byte[] ARRAY_CLOSE = "]".getBytes();
    /**
     * The open stream token.
     */
    public static final byte[] STREAM = "stream".getBytes();
    /**
     * The close stream token.
     */
    public static final byte[] ENDSTREAM = "endstream".getBytes();

    private NumberFormat formatXrefOffset = new DecimalFormat("0000000000");
    /**
     * The decimal format for the xref object generation number data.
     */
    private NumberFormat formatXrefGeneration = new DecimalFormat("00000");

    private NumberFormat formatDecimal = NumberFormat.getNumberInstance( Locale.US );

    // the stream used to write standard cos data
    private COSStandardOutputStream standardOutput;

    /**
     * COSWriter constructor comment.
     *
     * @param os The wrapped output stream.
     */
    public COSWriterPDF(OutputStream os)
    {
        super(os);
        setStandardOutput(new COSStandardOutputStream(getOutput()));
        formatDecimal.setMaximumFractionDigits( 10 );
        formatDecimal.setGroupingUsed( false );
    }

    /**
     * This will close the stream.
     *
     * @throws IOException If the underlying stream throws an exception.
     */
    public void close() throws IOException
    {
        if (getStandardOutput() != null)
        {
            getStandardOutput().close();
        }
        if (getOutput() != null)
        {
            getOutput().close();
         }
    }

    /**
     * This will get the standard output stream.
     *
     * @return The standard output stream.
     */
    protected COSStandardOutputStream getStandardOutput()
    {
        return standardOutput;
    }

    /**
     * This will set the standard output stream.
     *
     * @param newStandardOutput The new standard output stream.
     */
    private void setStandardOutput(COSStandardOutputStream newStandardOutput)
    {
        standardOutput = newStandardOutput;
    }

    public long getCurrentXRefPos() {
	return getStandardOutput().getPos();
    }

    public void objectStart( COSBase obj, COSObjectKey currentObjectKey ) throws IOException
    {
	getStandardOutput().write(String.valueOf(currentObjectKey.getNumber()).getBytes());
	getStandardOutput().write(SPACE);
	getStandardOutput().write(String.valueOf(currentObjectKey.getGeneration()).getBytes());
	getStandardOutput().write(SPACE);
	getStandardOutput().write(OBJ);
	getStandardOutput().writeEOL();
    }
    public void objectEnd( COSBase obj) throws IOException
    {
	getStandardOutput().writeEOL();
	getStandardOutput().write(ENDOBJ);
	getStandardOutput().writeEOL();
    }

    public void objectWrite(COSString obj) throws IOException
    {
	obj.writePDF( getStandardOutput() );
    }
    public void objectWrite(COSBoolean obj) throws IOException
    {
	obj.writePDF( getStandardOutput() );
    }
    public void objectWrite(COSFloat obj) throws IOException {
	obj.writePDF( getStandardOutput() );
    }
    public void objectWrite(COSInteger obj) throws IOException
    {
	obj.writePDF( getStandardOutput() );
    }
    public void objectWrite(COSName obj) throws IOException
    {
	obj.writePDF( getStandardOutput() );
    }
    public void objectWrite(COSNull obj) throws IOException
    {
	obj.writePDF( getStandardOutput() );
    }

    public void documentStart(COSDocument doc) throws IOException
    {
    }
    public void documentEnd() throws IOException
    {
    }
    public void bodyStart() throws IOException
    {
    }
    public void bodyEnd() throws IOException
    {
    }


    /**
     * This will write the header to the PDF document.
     *
     * @param doc The document to get the data from.
     *
     * @throws IOException If there is an error writing to the stream.
     */
    public void writeHeader(COSDocument doc) throws IOException
    {
        getStandardOutput().write( doc.getHeaderString().getBytes() );
        getStandardOutput().writeEOL();
        getStandardOutput().write(COMMENT);
        getStandardOutput().write(GARBAGE);
        getStandardOutput().writeEOL();
    }


    public void trailerStart() throws IOException 
    {
        getStandardOutput().write(TRAILER);
        getStandardOutput().writeEOL();
    }
    public void trailerEnd(long startXref) throws IOException
    {
        getStandardOutput().write(STARTXREF);
        getStandardOutput().writeEOL();
        getStandardOutput().write(String.valueOf(startXref).getBytes());
        getStandardOutput().writeEOL();
        getStandardOutput().write(EOF);
    }

    public void xrefStart(long lastKeyNumber) throws IOException
    {
        String offset;
        String generation;

        getStandardOutput().write(XREF);
        getStandardOutput().writeEOL();
        // write start object number and object count for this x ref section
        // we assume starting from scratch
        getStandardOutput().write(String.valueOf(0).getBytes());
        getStandardOutput().write(SPACE);
        getStandardOutput().write(String.valueOf(lastKeyNumber + 1).getBytes());
        getStandardOutput().writeEOL();
        // write initial start object with ref to first deleted object and magic generation number
        offset = formatXrefOffset.format(0);
        generation = formatXrefGeneration.format(65535);
        getStandardOutput().write(offset.getBytes());
        getStandardOutput().write(SPACE);
        getStandardOutput().write(generation.getBytes());
        getStandardOutput().write(SPACE);
        getStandardOutput().write(XREF_FREE);
        getStandardOutput().writeCRLF();
    }

    public void xrefEntryFree() throws IOException
    {
	String offset = formatXrefOffset.format(0);
	String generation = formatXrefGeneration.format(65535);
	getStandardOutput().write(offset.getBytes());
	getStandardOutput().write(SPACE);
	getStandardOutput().write(generation.getBytes());
	getStandardOutput().write(SPACE);
	getStandardOutput().write(XREF_FREE);
	getStandardOutput().writeCRLF();
    }

    public void xrefEntry(COSWriterXRefEntry entry) throws IOException
    {
	String offset = formatXrefOffset.format(entry.getOffset());
	String generation = formatXrefGeneration.format(entry.getKey().getGeneration());
	getStandardOutput().write(offset.getBytes());
	getStandardOutput().write(SPACE);
	getStandardOutput().write(generation.getBytes());
	getStandardOutput().write(SPACE);
	getStandardOutput().write(entry.isFree() ? XREF_FREE : XREF_USED);
	getStandardOutput().writeCRLF();
    }

    public void xrefEnd() throws IOException
    {
    }

    public void arrayStart(COSArray obj) throws IOException
    {
	getStandardOutput().write(ARRAY_OPEN);
    }

    public void arrayElementStart(int count) throws IOException
    {
    }
    public void arrayElementEnd(boolean hasNext, int count) throws IOException
    {
	if (!hasNext) return;
	if (count % 10 == 0)
	{
	    getStandardOutput().writeEOL();
	}
	else
        {
	    getStandardOutput().write(SPACE);
	}
    }
    public void arrayEnd() throws IOException
    {
	getStandardOutput().write(ARRAY_CLOSE);
	getStandardOutput().writeEOL();
    }

    public void dictStart() throws IOException
    {
	getStandardOutput().write(DICT_OPEN);
	getStandardOutput().writeEOL();
    }
    public void dictName(COSName name) throws IOException
    {
	objectWrite(name);
	getStandardOutput().write(SPACE);
    }
    public void dictPairEnd() throws IOException
    {
	getStandardOutput().writeEOL();
    }
    public void dictEnd() throws IOException
    {
	getStandardOutput().write(DICT_CLOSE);
	getStandardOutput().writeEOL();
    }


    // from inside Array or Dict
    public void writeRefKey(COSObjectKey key) throws IOException
    {
	getStandardOutput().write(String.valueOf(key.getNumber()).getBytes());
	getStandardOutput().write(SPACE);
	getStandardOutput().write(String.valueOf(key.getGeneration()).getBytes());
	getStandardOutput().write(SPACE);
	getStandardOutput().write(REFERENCE);
    }

    public void streamStart() throws IOException
    {
	getStandardOutput().write(STREAM);
	getStandardOutput().writeCRLF();
    }
    public void streamBlock(byte[] buffer, int amountRead) throws IOException
    {
	getStandardOutput().write( buffer, 0, amountRead );
    }
    public void streamEnd() throws IOException
    {
	getStandardOutput().writeCRLF();
	getStandardOutput().write(ENDSTREAM);
	getStandardOutput().writeEOL();
    }


}
