package gov.va.med.esr.common.util;

import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.Phase;


/**
 * @author DNS   faulkj
 */
public class CxfInInterceptor extends LoggingInInterceptor  {

	public CxfInInterceptor() {
        super(Phase.POST_LOGICAL);
    }

    @Override
    public void handleMessage(Message message) throws Fault {

    	InputStream is = (InputStream) message.getContent(InputStream.class);
        if (is != null) {
            CachedOutputStream bos = new CachedOutputStream();
            FileWriter f = null;
            InputStream istream = null;
            try {
                IOUtils.copy(is, bos);

                bos.flush();
                is.close();
                is = null;

                //message.setContent(InputStream.class, bos.getInputStream());

                //writePayload(buffer.getPayload(), bos, encoding, ct);
                f = new FileWriter (new File("cxfIN.intercept.txt"));
                f.append("Input message from IRS: \n");
                istream = bos.getInputStream();
                f.append(new String(IOUtils.toByteArray(istream)));
                //f.close();
                //f = null;
                //bos.close();
                //bos.getBytes();

                //bos.close();
            } catch (Exception e) {
                throw new Fault(e);
            } finally {
            	if (is != null) {
            		IOUtils.closeQuietly(is);
            	}             	
            	if (f != null) {
            		IOUtils.closeQuietly(f);
            	} 
            	if (istream != null) {
            		IOUtils.closeQuietly(istream);
            	}
            	IOUtils.closeQuietly(bos);

            }
        }


    	/*try {

    		FileWriter f = new FileWriter (new File("cxfIN.intercept.txt"));

            f.append(message.getContent(InputStream.class).toString());
            f.close();
        } catch (Exception ex) {

        }*/
    }



}