package com.xerox.vanguard;

import com.xerox.vanguard.rental.RentalAgreement;

import javax.xml.soap.SOAPBody;
// import javax.xml.soap.SOAPEnvelope;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
import org.w3c.dom.Element;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.Marshaller;

import java.util.Iterator;

import java.io.FileOutputStream;

public class PrintService {

	private Log log; 
	private JAXBContext context;
	private Unmarshaller unmarshaller;

	public PrintService(){
		this.log = LogFactory.getLog( PrintService.class.getName() );
		try {
			// this.context = JAXBContext.newInstance( "com.xerox.vanguard.rental" );
			// this.unmarshaller = context.createUnmarshaller();
			// this.log.info( "Created unmarshaller ok" );
		}catch( Exception e ){
			this.log.error( "Could not create unmarshaller", e );
		}
	}

	public void rental_agreement(SOAPEnvelope req, SOAPEnvelope resp){
		// eventually do something here with the attachments
		try { 
			log.info( "Got rental agreement request "); 
			SOAPBodyElement body = req.getFirstBody();
			log.info( "Body tag name is " + body.getTagName() );
		  Iterator iterator = body.getChildElements();
			while( iterator.hasNext() ){
				Object o = iterator.next();
				log.info( "Found child element " + o.getClass().getName() );
				if( o instanceof Element ){
					Element e = (Element)(o);
					log.info( "Child element tag name is " + e.getTagName() );
					log.info( "Child value is " + e );
				}
			}
			this.context = JAXBContext.newInstance( "com.xerox.vanguard.rental" );
			this.unmarshaller = context.createUnmarshaller();
			RentalAgreement agreement = (RentalAgreement)(unmarshaller.unmarshal( body.getRealElement() ));
			FileOutputStream file = new FileOutputStream( "agreement.out" );
			Marshaller marshaller = this.context.createMarshaller();
			marshaller.marshal( agreement, file );
			log.info( "Processing rental agreement number " + agreement.getRaNumber() );
		}catch( Exception e ){
			log.error( "Got exception on print request", e );
		}
	}
}
