package net.sourceforge.rtf.format;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;

import javax.imageio.ImageIO;

import net.sourceforge.rtf.context.image.FormatBase;
import net.sourceforge.rtf.context.image.ImageConstants;
import net.sourceforge.rtf.context.image.ImageWrapper;

import org.apache.commons.io.IOUtils;
/**
 * Description : Format for Input Stream.
 * @version 1.0.0
 * @author <a href="mailto:angelo.zerr@gmail.com">Angelo ZERR</a>
 */
public class DefaultInputStreamFormat extends Format {

	public static final long serialVersionUID = 1L;
	
	public StringBuffer format(Object arg0, StringBuffer arg1, FieldPosition arg2) {
		int width = 10160;
		int heigth = 6400;
		InputStream in = null;
		if (arg0 instanceof ImageWrapper) {
			ImageWrapper imageWrapper = (ImageWrapper)arg0;
			width = imageWrapper.getWidth();
			heigth = imageWrapper.getHeigth();
			in = imageWrapper.getImage();
		} else {
			in = (InputStream) arg0;
		}
		byte[] imagedata = null;
		try {
            imagedata = IOUtils.toByteArray(in);
		}
		catch (Exception e) {
        } finally {
            IOUtils.closeQuietly(in);
        }
        StringBuffer buf = new StringBuffer("");
        if (imagedata != null) {
        	// Test if image date is image
        	FormatBase imageformat = FormatBase.determineFormat(imagedata);
        	if (imageformat.getType() == ImageConstants.I_GIF) {
    			ByteArrayOutputStream baos;
				try {
					BufferedImage bi = ImageIO.read(new ByteArrayInputStream(imagedata));
					baos = new ByteArrayOutputStream();
					ImageIO.write(bi, "png", baos);
	                imagedata = baos.toByteArray();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        	
        	imageformat = FormatBase.determineFormat(imagedata);
            if (!(imageformat.getType() == ImageConstants.I_NOT_SUPPORTED
                    | imageformat.getRtfTag() == "")) 
            {
	        	buf = new StringBuffer(imagedata.length * 3);
		        for (int i = 0; i < imagedata.length; i++) {
		            int iData = imagedata [i];
		            // Make positive byte
		            if (iData < 0) {
		                iData += 256;
		            }
		            if (iData < 16) {
		                // Set leading zero and append
		                buf.append('0');
		            }
		            buf.append(Integer.toHexString(iData));
		        }
		        
		        buf.insert(0, "{\\*\\shppict{\\pict\\picwgoal" + width + "\\pichgoal" + heigth + "\\" + imageformat.getRtfTag() + " ");
 
		        buf.append("}");
		        buf.append("}");
            }
        }
        return buf;
	}
	
	public Object parseObject(String arg0, ParsePosition arg1) {
		// TODO Auto-generated method stub
		return null;
	}

}
