/**
 * 
 */
package at.gv.egiz.pdfas.impl.input;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.SequenceInputStream;

import at.gv.egiz.pdfas.framework.input.DataSource;
import at.gv.egiz.pdfas.framework.input.PdfDataSource;

/**
 * @author wprinz
 *
 */
public class CompoundPdfDataSourceImpl implements PdfDataSource
{
  protected DataSource originalDataSource = null;
  
  protected byte[] appendix = null;
  
  public CompoundPdfDataSourceImpl (PdfDataSource original, byte [] appendix)
  {
    this.originalDataSource = original;
    this.appendix = appendix;
  }

  /**
   * @see at.gv.egiz.pdfas.framework.input.DataSource#createInputStream()
   */
  public InputStream createInputStream()
  {
    ByteArrayInputStream bais = new ByteArrayInputStream(this.appendix);
    SequenceInputStream sis = new SequenceInputStream(this.originalDataSource.createInputStream(), bais);
    return sis;
  }

  /**
   * @see at.gv.egiz.pdfas.framework.input.DataSource#getLength()
   */
  public int getLength()
  {
    return this.originalDataSource.getLength() + this.appendix.length;
  }
  
  byte [] cache = null;

  /**
   * @see at.gv.egiz.pdfas.framework.input.DataSource#getAsByteArray()
   */
  public byte[] getAsByteArray()
  {
    if (cache != null)
    {
      return cache;
    }
    
    cache = new byte [getLength()];
    System.arraycopy(originalDataSource.getAsByteArray(), 0, cache, 0, originalDataSource.getLength());
    System.arraycopy(appendix, 0, cache, originalDataSource.getLength(), appendix.length);
    
    return cache;
  }
}