package com.example.mule.transformer;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractTransformer;
import org.mule.util.IOUtils;
import org.mule.util.StringUtils;

public class ToInputStream extends AbstractTransformer {

    static final String TARGET_ENCODING = "UTF-8";

    public ToInputStream() {
        registerSourceType(byte[].class);
        registerSourceType(InputStream.class);
        setReturnClass(InputStream.class);
    }

    protected Object doTransform(Object src, String encoding)
            throws TransformerException {
        try {
            String s;
            if (src == null) {
                s = StringUtils.EMPTY;
            } else if (src instanceof byte[]) {
                s = toString((byte[]) src, encoding);
            } else {
                s = toString((InputStream) src, encoding);
            }
            return toInputStream(s);
        } catch (Exception e) {
            throw new TransformerException(this, e);
        }
    }

    String toString(byte[] bytes, String encoding)
            throws UnsupportedEncodingException {
        return new String(bytes, encoding);
    }

    String toString(InputStream in, String encoding)
            throws UnsupportedEncodingException {
        return toString(toByteArray(in), encoding);
    }

    byte[] toByteArray(InputStream in) {
        try {
            return IOUtils.toByteArray(in);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    InputStream toInputStream(String s) {
        try {
            byte[] bytes = s.getBytes(TARGET_ENCODING);
            return new ByteArrayInputStream(bytes);
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }
    }

}
