package com.fractalite.hermes.teldar.cfg;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.converter.jaxb.JaxbDataFormat;
import org.apache.camel.model.language.JXPathExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.fractalite.hermes.services.stay.StayRouteBuilder;
import com.fractalite.hermes.teldar.Marshaller.MarshallingJAXB;
import com.fractalite.hermes.teldar.Marshaller.UnmarshallingJAXB;
import com.fractalite.hermes.teldar.parsers.BookingCancellationTeldResponse;
import com.fractalite.hermes.teldar.parsers.ParseAddBookingTeldar;
import com.fractalite.hermes.teldar.parsers.ParseConfirmBookResponse;
import com.fractalite.hermes.teldar.parsers.ParseHoteldetailsResponse;
import com.fractalite.hermes.teldar.parsers.ParseTeldarHotelsPriceResponse;
import com.fractalite.hermes.teldar.parsers.QuoteTeldarCancellationResponse;
import com.fractalite.hermes.teldar.services.CancelBookingsegmentTeldRequest;
import com.fractalite.hermes.teldar.services.ConfirmBookTeldarRequest;
import com.fractalite.hermes.teldar.services.GetHotelDetailsRequest;
import com.fractalite.hermes.teldar.services.HotelQuotesRequest;
import com.fractalite.hermes.teldar.services.PreBookingTeldarRequest;
import com.fractalite.hermes.teldar.services.QuoteTeldarRequestCancellation;
import com.fractalite.hermes.teldar.services.SearchTeldarHotelPriceRequest;
import com.fractalite.models.commerce.Order;
import com.fractalite.models.commerce.QuoteTemplate;
import com.fractalite.models.common.Address;
import com.fractalite.models.travel.stay.Hotel;
import com.fractalite.models.travel.stay.HotelStay;
import com.fractalite.models.travel.stay.StaySearchResults;
import com.gekko_holding.webservice.v2_4.CityBean;
import com.gekko_holding.webservice.v2_4.Facility;
import com.gekko_holding.webservice.v2_4.GeoLocalization;
import com.gekko_holding.webservice.v2_4.GetHotelDetailsResponse;
import com.gekko_holding.webservice.v2_4.HotelAvailability;
import com.gekko_holding.webservice.v2_4.HotelAvailabilityResponse;
import com.gekko_holding.webservice.v2_4.HotelBean;
import com.gekko_holding.webservice.v2_4.HotelBean.Facilities;
import com.gekko_holding.webservice.v2_4.HotelBean.Images;
import com.gekko_holding.webservice.v2_4.HotelChain;
import com.gekko_holding.webservice.v2_4.ImageUrl;

public class TeldarRouteBuilder extends RouteBuilder {
	public static final String EP_SEARCH = "teldar/hotel/search";
	public static final String EP_HOTEL_QUOTES = "teldar/hotel/quote";
	public static final String EP_HOTEL_ADDRESSE = "teldar/hotel/addresse";
	public static final String EP_HOTEL_INFO = "teldar/hotel/info";
	public static final String CHEK_AVAILABILITY = "teldar/hotel/chek";
	public static final String BOOK_HOTEL = "teldar/hotel/bookhotel";
	public static final String EP_HOTEL_QUOTE_CANCELLATION_POLICY = "teldar/hotel/hotelQuoteCancelleationFees";
	public static final String EP_CHARGE_CONDITIONS_BOOKING_LINE = "teldar/hotel/chargeConditionsBookingLine";
	public static final String EP_ORDER = "teldar/hotel/Order";
	public static final String EP_GET_ORDER = "teldar/hotel/getOrder";
	public static final String EP_BOOKING_CONFIRMATION = "teldar/hotel/bookingConfirmation";
	public static final String EP_CANCELLATION_FEES = "teldar/hotel/cancelleationFees";
	public static final String EP_CANCEL_ORDER = "teldar/hotel/cancelOrder";
	public static final String EP_MODIFY_ORDER = "teldar/hotel/modifyOrder";
	public static final String EP_MODIFY_ORDER_ITEM = "teldar/hotel/modifyOrderItem";
	public static final String EP_CANCEL_ORDER_ITEM = "teldar/hotel/cancelOrderItem";
	public static final String EP_SEARCH_ORDER = "teldar/hotel/searchOrder";
	public static final String EP_SEARCH_RESULT = "stay/searchResults";
	//public static final String wsUrl = "http4://teldar.atlasvoyages.com/gekko-front/ws/v2_4/AvailabilityService";
	public static final String wsUrl = "http4://localhost:8732/gekko-front/ws/v2_4/AvailabilityService";

	public String status = "";

	
	/////////////  TEST ////////////////:
	/*public static final String clientId = "atlasvoyages/master/test";
	public static final String password = "p*TE*kH!e8$%dS";
	public static final String customerKey = "atlasvoyages/test";*/

	////////////// END TEST ////////////
	
	/////////// TELDAR 
	/*public static final String clientId = "fractalite/master/tourcom9412web";
	public static final String password = "p*TE*kH!e8$%dS";
	public static final String customerKey = "fractalite/master";*/
	
	
	
/////////////  TEST UM ////////////////:
//public static final String clientId = "atlasvoyages/master/test";
//public static final String password = "p*TE*kH!e8$%dS";
//public static final String customerKey = "univairmer.creilcallcenter";
//"univairmer.chantilly";
	

/////////////  PROD UM ////////////////:
public static final String clientId = "fractalite/prod";
public static final String password = "p*TE*kH!e8$%dS";
//public static final String customerKey = "univairmer.creilcallcenter";
public static final String customerKey = "univairmer.tours";

//public static final String customerKey = "univairmer.chantilly";
//public static final String customerKey = "univairmer.tours";



/// Univairmer prod p*TE*kH!e8$%dS
// univairmer prod fractalite/prod



/*
/////////////  PROD Transco ////////////////:
public static final String clientId = "master/fractalite";
public static final String password = "T2eSnJ3sPEpFC2";
public static final String customerKey = "tourcom9412";
	
*/
	
	
	//Transco 
/*	public static final String clientId = "atlasvoyages/master/test";
	public static final String password = "p*TE*kH!e8$%dS";
	public static final String customerKey = "tourcom9412";*/

	org.apache.camel.spi.DataFormat jaxb = new org.apache.camel.converter.jaxb.JaxbDataFormat(
			"com.fractalite.hermes.teldar.api");

	private static final Logger logger = LoggerFactory.getLogger(TeldarRouteBuilder.class);

	private JaxbDataFormat hotelsDataFormat;

	private boolean test = false;

	public TeldarRouteBuilder() {

		super();
	}

	/**
	 * Constructor specifying if the routeBuilder is ran as test on production,
	 * public endpoints are exposed through NMR component to enable inter bundle
	 * communication on test , public endpoints are exposed through Direct component
	 * (nmr testing is confusing)
	 *
	 * @param test true if test
	 */
	public TeldarRouteBuilder(boolean test) {

		super();
		this.test = test;
	}

	public static String soapMessageBodyContent(String message) throws Exception {
		// create message factory
		MessageFactory messageFactory = MessageFactory.newInstance();

		// converting string body to stream.
		InputStream responseInputStream = new ByteArrayInputStream(message.getBytes());

		// getting saop body stream to create soap message instance
		SOAPMessage soapMessage = messageFactory.createMessage(null, responseInputStream);

		// get the body
		SOAPBody soapBody = soapMessage.getSOAPBody();

		return convertToString(soapBody);
	}
	

	/**
	 * Notes on search and quote routes : Since teldar does not handle multi room
	 * type reservation, split/aggregate is used to make results per each room type
	 */
	@Override
	public void configure() throws Exception {
		String nmrOrDirect = (test) ? "direct:" : "nmr:";
	
		// XML Data Format
		JaxbDataFormat availabilityReqDF = new JaxbDataFormat();
		JAXBContext context = JAXBContext.newInstance(HotelAvailability.class);
		availabilityReqDF.setContext(context);

		JaxbDataFormat details = new JaxbDataFormat();
		JAXBContext contexts = JAXBContext.newInstance(GetHotelDetailsResponse.class);
		details.setContext(contexts);

		/*************** SearchHotelsPriceRequest ******************/

		JAXBContext hotelsContext = JAXBContext.newInstance(HotelAvailabilityResponse.class);
		hotelsDataFormat = new JaxbDataFormat();
		hotelsDataFormat.setContext(hotelsContext);
		hotelsDataFormat.setEncoding("UTF-8");

		from(nmrOrDirect + EP_SEARCH).routeId(EP_SEARCH).setExchangePattern(ExchangePattern.InOut)
				.log("Contacting search webservice !!!!!  ${body}").choice()
				// stop if morocco
				.when(new JXPathExpression("in/body/trip/content[1]/hotel/address/country/code = ''")).otherwise()

				.process(new Processor() {

					@Override
					public void process(Exchange exchange) throws Exception {
						QuoteTemplate q = exchange.getIn().getMandatoryBody(QuoteTemplate.class);
						HotelStay hotelstay = q.getTrip().getContent(HotelStay.class).get(0);
					//	if ((hotelstay.getHotel()!=null && hotelstay.getHotel().getAddress()!= null  && !hotelstay.getHotel().getAddress().getLocality().getCode().startsWith("geo")) && (hotelstay.getGiatacode() == null  || hotelstay.getGiatacode().getGekko_teldar() == null ||  hotelstay.getGiatacode().getGekko_teldar().size() == 0))
					//		exchange.getIn().setHeader("teldaremtygiata", true);
					//	else
					//		exchange.getIn().setHeader("teldaremtygiata", false);
					}
				})
				/*.choice()
				// stop if code empty
				.when(header("teldaremtygiata").isEqualTo(true))
				.log("teldar Giata code is null")
				.removeHeader("teldaremtygiata")
				.process(new Processor() {

					@Override
					public void process(Exchange exchange) throws Exception {
						StaySearchResults result = new StaySearchResults();
						result.setQuery(exchange.getIn().getBody(QuoteTemplate.class));
						exchange.getIn().setBody(result);
					}
				}).to(nmrOrDirect + StayRouteBuilder.EP_SEARCH_RESULT).stop()

				.otherwise()*/
				.log("teldar Giata code is NOT null")
				.setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.POST))
				.setHeader(Exchange.CONTENT_TYPE, constant("application/xml"))
				.setHeader(Exchange.SOAP_ACTION, constant("")).process(new Processor() {

					@Override
					public void process(Exchange exchange) throws Exception {

						for (String h : exchange.getIn().getHeaders().keySet())
							logger.info("\n header before serach " + h + " : " + exchange.getIn().getHeader(h));
						exchange.setProperty("linkheader", exchange.getIn().getHeader("Link"));
						exchange.setProperty("hermessearchcompletionsize",
								exchange.getIn().getHeader("hermessearchcompletionsize"));
					}
				})
				.log("teldar before calliong  SearchTeldarHotelPriceRequest")

				.process(new SearchTeldarHotelPriceRequest())
				
				.split(body(), new StaySearchResultsSimpleAggregator()).parallelProcessing()
					.bean(MarshallingJAXB.class, "marshallObject")
					.log("\n Request body content : \n ${body}")
					//.log("urlllll" + wsUrl)
					 .to(wsUrl)
					 .convertBodyTo(String.class, "ISO-8859-1")
					// .convertBodyTo(String.class, "UTF-8")
					 .process(new Processor() {
							@Override
							public void process(Exchange exchange) throws Exception {
								exchange.getIn().setHeaders(new HashMap<String, Object>());
								exchange.getIn().setHeader("Link", exchange.getProperty("linkheader"));

								exchange.getIn().setHeader("hermessearchcompletionsize",
										exchange.getProperty("hermessearchcompletionsize"));

								soapMessageBodyContent(exchange.getIn().getBody(String.class));

								logger.info("unmarshledSoap" + soapMessageBodyContent(exchange.getIn().getBody(String.class)));
							}
						})

						/* Unmarshalling teldar response */
						.bean(UnmarshallingJAXB.class, "fromHotelAvailabilityResponse(${body})")
						.process(new ParseTeldarHotelsPriceResponse())
				 .log("\n teldar response body --------------- : \n ${body}")
				 .end()
				
				
				 
			//	.end()
				.process(new Processor() {
					
					@Override
					public void process(Exchange exchange) throws Exception {
						
						StaySearchResults htls=	exchange.getIn().getBody(StaySearchResults.class);
						log.info("the final hotels list is "+htls.getHotels().size());
						exchange.getIn().setBody(htls, StaySearchResults.class);
						exchange.getOut().setBody(htls, StaySearchResults.class);

					}
				})
				//.to(nmrOrDirect + EP_SEARCH_RESULT)
				;

		/***************** HotelQuotesRequest *******************/

		from(nmrOrDirect + EP_HOTEL_QUOTES).routeId(EP_HOTEL_QUOTES).setExchangePattern(ExchangePattern.InOut)
						
				.setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.POST))
				.setHeader(Exchange.CONTENT_TYPE, constant("application/xml"))
				.setHeader(Exchange.SOAP_ACTION, constant(""))

				.process(new HotelQuotesRequest())
				
				.process(new Processor() {

					@Override
					public void process(Exchange exchange) throws Exception {
						for (String h : exchange.getIn().getHeaders().keySet())
							logger.info("header before quote " + h + " :  " + exchange.getIn().getHeader(h));
					}
				})

				.bean(MarshallingJAXB.class, "marshallObject")
				.log("\n Request bodyquoteee content : \n ${body}")
				.to(wsUrl)

				//.convertBodyTo(String.class, "ISO-8859-1")
				.convertBodyTo(String.class, "UTF-8")

				.process(new Processor() {

					@Override
					public void process(Exchange exchange) throws Exception {
						exchange.getIn().setHeaders(new HashMap<String, Object>());
						logger.info("UnmashalledQuoteeeee response body : ---------- \n "
								+ soapMessageBodyContent(exchange.getIn().getBody(String.class)));
					}
				})
				.bean(UnmarshallingJAXB.class, "fromHotelAvailabilityResponse(${body})")

				.log("ResponseMarshllerQuote --------------- : \n ${body}")
				.process(new com.fractalite.hermes.teldar.parsers.ParserQuotesresponse())
	            .log("bodyquoteeee --------------- : \n ${body}")
				;
				

		/***************** HotelDetailsInfo *******************/

		from(nmrOrDirect + EP_HOTEL_INFO)
		.routeId(EP_HOTEL_INFO)
		.setExchangePattern(ExchangePattern.InOut)
	
		         .removeHeaders("*")
				.setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.POST))
				.setHeader(Exchange.CONTENT_TYPE, constant("application/xml"))
				.setHeader(Exchange.SOAP_ACTION, constant("")).process(new GetHotelDetailsRequest())

				.log("bodyDetailss2 : \n ${body}")
				.bean(MarshallingJAXB.class, "marshallObject")
				.to(wsUrl)
				.convertBodyTo(String.class, "ISO-8859-1")
				.log("ResponseDetails2 --------------- : \n ${body}")

				.process(new Processor() {

					@Override
					public void process(Exchange exchange) throws Exception {
						exchange.getIn().setHeaders(new HashMap<String, Object>());

						logger.info("ConvertionNode1"
								+ ConvertionNode(soapMessageBodyContent(exchange.getIn().getBody(String.class))));
						exchange.getOut().setBody(
								ConvertionNode(soapMessageBodyContent(exchange.getIn().getBody(String.class))));

					}
				})

			//	 .bean(UnmarshallingJAXB.class, "fromGetDetailsResponse(${body})")
				.process(new ParseHoteldetailsResponse())
				.log("responsemeeeedd-------------- : \n ${body}");


		
		/***************** HotelQuotesCancellationPolicyRequest *******************/
		
		from(nmrOrDirect + EP_HOTEL_QUOTE_CANCELLATION_POLICY)
    	.routeId(EP_HOTEL_QUOTE_CANCELLATION_POLICY)
    	.setExchangePattern(ExchangePattern.InOut)
		.removeHeaders("*")
		.setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.POST))
		.setHeader(Exchange.CONTENT_TYPE, constant("application/xml"))
		.setHeader(Exchange.SOAP_ACTION, constant(""))
		.process(new QuoteTeldarRequestCancellation())
		.bean(MarshallingJAXB.class, "marshallObject")
		.log("cancelRequestTeldar body --------------- : \n ${body}")
		.to(wsUrl)
		.convertBodyTo(String.class)
		.log("Cancelresponse body --------------- : \n ${body}")
		.bean(UnmarshallingJAXB.class, "fromHotelAvailabilityResponse(${body})")
        .process(new QuoteTeldarCancellationResponse()) ;

		/***************** PreBookingHotelRequest *******************/

		from(nmrOrDirect + EP_ORDER)
		.routeId(EP_ORDER).setExchangePattern(ExchangePattern.InOut)
		.removeHeaders("*")
		.setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.POST))
		.setHeader(Exchange.CONTENT_TYPE, constant("application/xml"))
		.setHeader(Exchange.SOAP_ACTION, constant(""))
		.process(new PreBookingTeldarRequest())
		.bean(MarshallingJAXB.class, "marshallObject")
		.log("PreBookTeldar body --------------- : \n ${body}")
		.to(wsUrl)
		.convertBodyTo(String.class)
		.log("ResponsePreOrderBOok --------------- : \n ${body}")
		.process(new Processor() {

			@Override
			public void process(Exchange exchange) throws Exception {
				exchange.getIn().setHeaders(new HashMap<String, Object>());
				soapMessageBodyContent(exchange.getIn().getBody(String.class));

				logger.info("unmarshledSoapPreBOOK" + soapMessageBodyContent(exchange.getIn().getBody(String.class)));

			}
		})
			.bean(UnmarshallingJAXB.class, "fromPreBookingInfoResponse(${body})")
		.log("ResponseUnMarshllerPreOder --------------- : \n ${body}")
		.process(new ParseAddBookingTeldar())
		;



									
///////////////////EP_BOOKING_CONFIRMATION////////////////////////////
		from(nmrOrDirect + EP_BOOKING_CONFIRMATION)
		// from("timer://orderTimer?delay=6000&repeatCount=1")
		.routeId(EP_BOOKING_CONFIRMATION)
		.setExchangePattern(ExchangePattern.InOut)
		.removeHeaders("*")
		.setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.POST))
		.setHeader(Exchange.CONTENT_TYPE, constant("application/xml"))
		.setHeader(Exchange.SOAP_ACTION, constant(""))
		.process(new ConfirmBookTeldarRequest())
		.bean(MarshallingJAXB.class, "marshallObject")
		.log("Response Marshller--------------- : \n ${body}")
		.to(wsUrl)
		.convertBodyTo(String.class)
		.log("ConfirmBookTeldarRequest Response body --------------- : \n ${body}")
		.bean(UnmarshallingJAXB.class, "fromBookHotelResponse(${body})")
		.log("ResponseUmarshledConfirm --------------- : \n ${body}")
		.process(new ParseConfirmBookResponse())
		.log("ResponseConfirmed ---------- : \n ${body}")
		.removeHeaders("*")
		.removeHeaders("camel*")
		.process(new Processor() {	
			@Override
			public void process(Exchange exchange) throws Exception {
				Order order = exchange.getIn().getMandatoryBody(Order.class);
				 exchange.getIn().setBody(order.getTrip().getContent(HotelStay.class).get(0).getHotel().getCode());	
				
			}
		})
		.log("ResponseParserBook ---------- : \n ${body}")
		.to(nmrOrDirect + EP_HOTEL_INFO)
		.log("detailhotellllls ---------- : \n ${body}")
		.process(new Processor() {
				
				@Override
				public void process(Exchange exchange) throws Exception {
					Hotel hermesHotel =exchange.getIn().getMandatoryBody(Hotel.class);
					Order order=  exchange.getProperty("order", Order.class);
					
					Hotel h = new Hotel(hermesHotel.getCode(), hermesHotel.getName());
					log.info("From info "+hermesHotel.getCode() +"   and    "+ hermesHotel.getName() );
				//	h.setAddress(hermesHotel.getAddress());
					Address adr = new Address(hermesHotel.getAddress().getStreet(), hermesHotel.getAddress().getZipcode(),null, null);
					h.setAddress(adr);
					order.getTrip().getContent(HotelStay.class).get(0).setHotel( h);
					exchange.getIn().setBody(order, Order.class);
				}
			})
		;
		

				
				
		
		
		/***************** HotelChargeConditionsBookingRequest *******************/
		/***************** HotelChargeConditionsBookingRequest *******************/

		from(nmrOrDirect + EP_CANCELLATION_FEES)
		.routeId(EP_CANCELLATION_FEES)
		.setExchangePattern(ExchangePattern.InOut)
		.log("TeldarCancelFeess --------------- : \n ${body}")
   .process(new Processor() {
			
			@Override
			public void process(Exchange exchange) throws Exception {
				exchange.getIn().setBody("Please reed cancellation policies");
			}})
		;

		/***************** HotelQuotesCancellationPolicyRequest *******************/

		from(nmrOrDirect + EP_HOTEL_QUOTE_CANCELLATION_POLICY).routeId(EP_HOTEL_QUOTE_CANCELLATION_POLICY)
				.setExchangePattern(ExchangePattern.InOut);

		/***************** CancelBookingRequest *******************/

		from(nmrOrDirect + EP_CANCEL_ORDER)
		.routeId(EP_CANCEL_ORDER)
		.setExchangePattern(ExchangePattern.InOut)
		.log("AccorCancelBookingRequest --------------- : \n ${body}")
		.setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.POST))
		.setHeader(Exchange.CONTENT_TYPE, constant("application/xml"))
		.setHeader(Exchange.SOAP_ACTION, constant(""))
		.process(new CancelBookingsegmentTeldRequest())
		.convertBodyTo(String.class)
		.log("Requestbodyyyyy --------------- : \n ${body}")
		//.bean(MarshallingJAXB.class, "marshallObject")
		.to(wsUrl)
		.convertBodyTo(String.class)
		.log("TeldarCancelBookingRequestbody --------------- : \n ${body}")
		.bean(UnmarshallingJAXB.class, "fromBookingCancellation(${body})")
		.process(new BookingCancellationTeldResponse());

	}

	private static GetHotelDetailsResponse ConvertionNode(String hoteldetail)
			throws ParserConfigurationException, SAXException, IOException, JAXBException, TransformerException {
		Logger logg = LoggerFactory.getLogger(TeldarRouteBuilder.class);
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
		builder = factory.newDocumentBuilder();
		Document document = builder.parse(new InputSource(new StringReader(hoteldetail)));
		Element rootElement = document.getDocumentElement();

		logger.info("detailsssssssssssss" +hoteldetail);
		logger.info("documentDetailss" +rootElement);
		GetHotelDetailsResponse resp = new GetHotelDetailsResponse();

		NodeList nLhotelName = rootElement.getElementsByTagName("hotelName");

		Element elmnhotelName = (Element) nLhotelName.item(0);

		Node nLhotelCode = rootElement.getAttributeNode("hotelCode");

		String hotelCode ="";
		
		if(rootElement.getAttributeNode("hotelCode")!= null) {
			hotelCode =nLhotelCode.getNodeValue().toString();
			
		}
		logger.info("hotelcodehotel" +nLhotelCode) ;
		
		Node nLhotelRating = rootElement.getAttributeNode("hotelRating");

		String hotelRating ="";
		
		if(rootElement.getAttributeNode("hotelRating") !=null) {
			hotelRating=nLhotelRating.getNodeValue();
			logger.info("hotelRatinggggggggggg" +nLhotelRating) ;

		}
		HotelChain htlChaine = new HotelChain();
		NodeList nLhotelChain = rootElement.getElementsByTagName("hotelChain");

		Element elmnhotelChain = (Element) nLhotelChain.item(0);
		if (elmnhotelChain != null && elmnhotelChain.getTextContent() != null) {
			String hotelChain = elmnhotelChain.getTextContent();
			htlChaine.setValue(hotelChain);
		}
		logger.info("nLhotelChainnnn" +nLhotelChain) ;
		logger.info("hotelChainnnn" +elmnhotelChain) ;
		
		CityBean cityB = new CityBean();
		NodeList nLcity = rootElement.getElementsByTagName("city");

		Element elmncity = (Element) nLcity.item(0);
		Node nLCode = elmncity.getAttributeNode("code");

		String codeCity = "";
		if(elmncity.getAttributeNode("code") !=null) {
			codeCity = nLCode.getNodeValue();
			logger.info("codeCityyyyyy" +nLCode);
		}
		logger.info("codeCityyyyyy2" +nLCode);
		
		cityB.setCode(codeCity);

		GeoLocalization geo = new GeoLocalization();
		NodeList nLgeoLocalization = rootElement.getElementsByTagName("geoLocalization");

		Element elmngeoLocalization = (Element) nLgeoLocalization.item(0);
		Node nLlatitude = elmngeoLocalization.getAttributeNode("latitude");
		double latitude = Double.valueOf(nLlatitude.getNodeValue().toString());
		Node nLlongitude = elmngeoLocalization.getAttributeNode("longitude");
		double longitude = Double.valueOf(nLlongitude.getNodeValue());
		geo.setLatitude(latitude);
		geo.setLongitude(longitude);

		NodeList nLaddress = rootElement.getElementsByTagName("address");

		Element elmnaddress = (Element) nLaddress.item(0);

		NodeList nLphone = rootElement.getElementsByTagName("phone");

		Element elmnphone = (Element) nLphone.item(0);

		NodeList nLfax = rootElement.getElementsByTagName("fax");

		Element elmnfax = (Element) nLfax.item(0);

		NodeList nLemail = rootElement.getElementsByTagName("email");

		Element elmnemail = (Element) nLemail.item(0);

		NodeList nLshortDescription = rootElement.getElementsByTagName("shortDescription");

		Element elmnshortDescription = (Element) nLshortDescription.item(0);

		NodeList nLthumbnailUrl = rootElement.getElementsByTagName("thumbnailUrl");

		Element elmnthumbnailUrl = (Element) nLthumbnailUrl.item(0);

		NodeList nLfacilities = rootElement.getElementsByTagName("facilities");
		Facilities fclt = new Facilities();
		for (int i = 0; i < nLfacilities.getLength(); i++) {
			Facility fac = new Facility();

			Element elmnfacilities = (Element) nLfacilities.item(i);
			NodeList nLfacility = elmnfacilities.getElementsByTagName("facility");
			Element elmnfacility = (Element) nLfacility.item(0);

			Node nLCodeFacilities = elmnfacility.getAttributeNode("code");

			for (int j = 0; j < nLfacility.getLength(); j++) {
				Element elmnFac = (Element) nLfacility.item(j);
				// String typeImage = elmnImage.getNodeValue();
				Node cd = elmnFac.getAttributeNode("code");

				String faci = cd.getNodeValue();
				String facivalue = elmnFac.getTextContent();

				Facility fct = new Facility();
				fct.setCode(faci);
				fct.setValue(facivalue);
				fclt.getFacility().add(fct);
			}
			String codeFacility = nLCodeFacilities.getNodeValue();

			fac.setCode(codeFacility);
			fclt.getFacility().add(fac);

		}

		NodeList nLimages = rootElement.getElementsByTagName("images");
		Images imges = new Images();
		List<ImageUrl> igs = new ArrayList<ImageUrl>();
		List<String> str = new ArrayList<String>();

		for (int i = 0; i < nLimages.getLength(); i++) {
			ImageUrl ig = new ImageUrl();
			Element elmnImages = (Element) nLimages.item(i);
			NodeList nLImage = elmnImages.getElementsByTagName("image");
			Element elmnfacility = (Element) nLImage.item(0);
			Node nLTypeImages = elmnfacility.getAttributeNode("type");
			for (int j = 0; j < nLImage.getLength(); j++) {
				Element elmnImage = (Element) nLImage.item(j);

				String urlImage = elmnImage.getTextContent();
				ig.setValue(urlImage);
				str.add(ig.getValue());
				igs.add(ig);
			}

		}

		for (int j = 0; j < str.size(); j++) {
			ImageUrl igt = new ImageUrl();
			igt.setValue(str.get(j));
			imges.getImage().add(igt);
		}

		// String strObject = result.getWriter().toString() ;
		String hotelName = elmnhotelName.getTextContent();
		String city = elmncity.getTextContent();
		String geoLocalization = elmngeoLocalization.getTextContent();
		String address = elmnaddress.getTextContent();
		
		String phone = "";
		if(elmnphone!=null && elmnphone.getTextContent()!=null)
			phone=elmnphone.getTextContent();
		String fax = "";
		String email = "";
		String shortDescription = "";
		String thumbnailUrl = "";

		if (elmnfax != null && elmnfax.getTextContent() != null)
			fax = elmnfax.getTextContent();
        logger.info("faxxxxxxx" +nLfax);

		if (elmnemail != null && elmnemail.getTextContent() != null)
			email = elmnemail.getTextContent();

		if (elmnshortDescription != null && elmnshortDescription.getTextContent() != null)
			shortDescription = elmnshortDescription.getTextContent();

		if (elmnthumbnailUrl != null && elmnthumbnailUrl.getTextContent() != null)
			thumbnailUrl = elmnthumbnailUrl.getTextContent();

		HotelBean htlB = new HotelBean();
		htlB.setHotelName(hotelName);
		htlB.setHotelCode(hotelCode);
		htlB.setHotelRating(hotelRating); //
		htlB.setHotelChain(htlChaine);
		htlB.setAddress(address);
		htlB.setFax(fax);

		htlB.setPhone(phone);
		htlB.setEmail(email);
		htlB.setGeoLocalization(geo);
		htlB.setFacilities(fclt);
		htlB.setImages(imges);
		htlB.setShortDescription(shortDescription);
		htlB.setThumbnailUrl(thumbnailUrl);
		htlB.setCity(cityB);

		resp.getHotel().add(htlB);

		return resp;
	}

		
	public static Document stringToXml(String line) throws ParserConfigurationException, SAXException, IOException {
		Logger logg = LoggerFactory.getLogger(TeldarRouteBuilder.class);

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(new InputSource(new StringReader(line)));

		return document;
	}

//ConvertString
	private static String convertToString(SOAPBody message) throws Exception {

		Document doc = message.extractContentAsDocument();
		Element rootElement = doc.getDocumentElement();
		NodeList nList11 = rootElement.getElementsByTagName("hotel");
		Node m = nList11.item(0);
		Element s = (Element) m;

		StringWriter sw = new StringWriter();
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		transformer.setOutputProperty(OutputKeys.METHOD, "xml");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		transformer.transform(new DOMSource(s), new StreamResult(sw));
		return sw.toString();

	}

}