/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the docs/licenses/apache-1.1.txt file.
 */
package org.jboss.axis.attachments;

import org.jboss.axis.components.image.ImageIOFactory;
import org.jboss.axis.utils.Messages;
import org.jboss.logging.Logger;

import javax.activation.DataSource;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ImageDataSource implements DataSource
{
   private static Logger log = Logger.getLogger(ImageDataSource.class.getName());

   public static final String CONTENT_TYPE = "image/jpeg";

   private final String name;
   private final String contentType;
   private byte[] data;
   private ByteArrayInputStream is;
   private ByteArrayOutputStream os;

   public ImageDataSource(String name, Image data)
   {
      this(name, CONTENT_TYPE, data);
   } // ctor

   public ImageDataSource(String name, String contentType, Image data)
   {
      this.name = name;
      this.contentType = contentType == null ? CONTENT_TYPE : contentType;
      os = new ByteArrayOutputStream();
      try
      {
         if (data != null)
         {
            ImageIOFactory.getImageIO().saveImage(this.contentType, data, os);
         }
      }
      catch (Exception e)
      {
         log.error(Messages.getMessage("exception00"), e);
      }
   } // ctor

   public String getName()
   {
      return name;
   } // getName

   public String getContentType()
   {
      return contentType;
   } // getContentType

   public InputStream getInputStream() throws IOException
   {
      if (os.size() != 0)
      {
         data = os.toByteArray();
         os.reset();
      }
      return new ByteArrayInputStream(data == null ? new byte[0] : data);
   } // getInputStream

   public OutputStream getOutputStream() throws IOException
   {
      if (os.size() != 0)
      {
         data = os.toByteArray();
         os.reset();
      }
      return os;
   } // getOutputStream
} // class ImageDataSource
