from helper import *
import pdb
from time import sleep


def start_session(pccToEmulate="6B3D"):
    body = \
        """
    <SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:eb='http://www.ebxml.org/namespaces/messageHeader' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/1999/XMLSchema'>
       <SOAP-ENV:Header>
          <eb:MessageHeader SOAP-ENV:mustUnderstand='1' eb:version='1.0'>
             <eb:From>
                <eb:PartyId type='urn:x12.org:IO5:01'>999999</eb:PartyId>
             </eb:From>
             <eb:To>
                <eb:PartyId type='urn:x12.org:IO5:01'>123123</eb:PartyId>
             </eb:To>
             <eb:CPAId>6B3D</eb:CPAId>
             <eb:ConversationId>TEST-6B3D</eb:ConversationId>
             <eb:Service eb:type='OTA'>SessionCreateRQ</eb:Service>
             <eb:Action>SessionCreateRQ</eb:Action>
             <eb:MessageData>
                <eb:MessageId>170390</eb:MessageId>
                <eb:Timestamp>2012-06-07T10:00:00</eb:Timestamp>
                <eb:TimeToLive>2013-06-06T23:59:59</eb:TimeToLive>
             </eb:MessageData>
          </eb:MessageHeader>
          <wsse:Security xmlns:wsse='http://schemas.xmlsoap.org/ws/2002/12/secext' xmlns:wsu='http://schemas.xmlsoap.org/ws/2002/12/utility'>
             <wsse:UsernameToken>
                <wsse:Username>170390</wsse:Username>
                <wsse:Password>WS793581</wsse:Password>
                <Organization>6B3D</Organization>
                <Domain>DEFAULT</Domain>
             </wsse:UsernameToken>
          </wsse:Security>
       </SOAP-ENV:Header>
       <SOAP-ENV:Body>
          <SessionCreateRQ>
             <POS>
                <Source PseudoCityCode='6B3D'/>
             </POS>
          </SessionCreateRQ>
       </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
    """
    response = requests.post(url, data=body, headers=headers)

    # print response.content;

    root = ET.fromstring(response.content)
    # print response.content
    secToken = root[0][-1][0].text

    if pccToEmulate !='6B3D':
        body = \
            """ <SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:eb='http://www.ebxml.org/namespaces/messageHeader' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/1999/XMLSchema'>
        <SOAP-ENV:Header>
            <eb:MessageHeader SOAP-ENV:mustUnderstand='1' eb:version='2.0'>
                <eb:From>
                    <eb:PartyId type='urn:x12.org:IO5:01'>1212</eb:PartyId>
                </eb:From>
                <eb:To>
                    <eb:PartyId type='urn:x12.org:IO5:01'>2323</eb:PartyId>
                </eb:To>
                <eb:CPAId>6B3D</eb:CPAId>
                <eb:ConversationId>TEST-6B3D</eb:ConversationId>
                <eb:Service eb:type='OTA'>ContextChangeLLSRQ</eb:Service>
                <eb:Action>ContextChangeLLSRQ</eb:Action>
                <eb:MessageData>
                    <eb:MessageId>1001</eb:MessageId>
                    <eb:Timestamp>2012-06-07T10:00:01</eb:Timestamp>
                    <eb:TimeToLive>2013-06-06T23:59:59</eb:TimeToLive>
                </eb:MessageData>
            </eb:MessageHeader>
            <wsse:Security xmlns:wsse='http://schemas.xmlsoap.org/ws/2002/12/secext' xmlns:wsu='http://schemas.xmlsoap.org/ws/2002/12/utility'>
                <wsse:BinarySecurityToken valueType='String' EncodingType='wsse:Base64Binary'>""" \
            + secToken \
            + """</wsse:BinarySecurityToken>
            </wsse:Security>
        </SOAP-ENV:Header>
        <SOAP-ENV:Body>
            <ContextChangeRQ xmlns="http://webservices.sabre.com/sabreXML/2011/10" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="2.0.3">
    <ChangeAAA PseudoCityCode='"""+pccToEmulate+"""'/>
    </ContextChangeRQ>
        </SOAP-ENV:Body>
        </SOAP-ENV:Envelope> """
        response = requests.post(url, data=body, headers=headers)
    print 'Session started ... ' + pccToEmulate
    return secToken


def stop_session(secToken):
    body = \
        """ <SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:eb='http://www.ebxml.org/namespaces/messageHeader' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/1999/XMLSchema'>
       <SOAP-ENV:Header>
          <eb:MessageHeader SOAP-ENV:mustUnderstand='1' eb:version='2.0'>
             <eb:From>
                <eb:PartyId type='urn:x12.org:IO5:01'>1212</eb:PartyId>
             </eb:From>
             <eb:To>
                <eb:PartyId type='urn:x12.org:IO5:01'>2323</eb:PartyId>
             </eb:To>
             <eb:CPAId>6B3D</eb:CPAId>
             <eb:ConversationId>TEST-6B3D</eb:ConversationId>
             <eb:Service eb:type='OTA'>SessionCloseRQ</eb:Service>
             <eb:Action>SessionCloseRQ</eb:Action>
             <eb:MessageData>
                <eb:MessageId>1001</eb:MessageId>
                <eb:Timestamp>2012-06-07T10:00:01</eb:Timestamp>
                <eb:TimeToLive>2013-06-06T23:59:59</eb:TimeToLive>
             </eb:MessageData>
          </eb:MessageHeader>
          <wsse:Security xmlns:wsse='http://schemas.xmlsoap.org/ws/2002/12/secext' xmlns:wsu='http://schemas.xmlsoap.org/ws/2002/12/utility'>
             <wsse:BinarySecurityToken valueType='String' EncodingType='wsse:Base64Binary'>""" \
        + secToken \
        + """</wsse:BinarySecurityToken>
          </wsse:Security>
       </SOAP-ENV:Header>
       <SOAP-ENV:Body>
          <SessionCloseRQ>
             <POS>
                <Source PseudoCityCode='6B3D'/>
             </POS>
          </SessionCloseRQ>
       </SOAP-ENV:Body>
    </SOAP-ENV:Envelope> """
    response = requests.post(url, data=body, headers=headers)
    print 'Session stopped ...'

    return response.content


def ticket(secToken, doc_no):
    log()
    body = \
        """ <SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:eb='http://www.ebxml.org/namespaces/messageHeader' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/1999/XMLSchema'>
       <SOAP-ENV:Header>
          <eb:MessageHeader SOAP-ENV:mustUnderstand='1' eb:version='2.0'>
             <eb:From>
                <eb:PartyId type='urn:x12.org:IO5:01'>1212</eb:PartyId>
             </eb:From>
             <eb:To>
                <eb:PartyId type='urn:x12.org:IO5:01'>2323</eb:PartyId>
             </eb:To>
             <eb:CPAId>6B3D</eb:CPAId>
             <eb:ConversationId>TEST-6B3D</eb:ConversationId>
             <eb:Service eb:type='OTA'>eTicketCouponLLSRQ</eb:Service>
             <eb:Action>eTicketCouponLLSRQ</eb:Action>
             <eb:MessageData>
                <eb:MessageId>1001</eb:MessageId>
                <eb:Timestamp>2012-06-07T10:00:01</eb:Timestamp>
                <eb:TimeToLive>2013-06-06T23:59:59</eb:TimeToLive>
             </eb:MessageData>
          </eb:MessageHeader>
          <wsse:Security xmlns:wsse='http://schemas.xmlsoap.org/ws/2002/12/secext' xmlns:wsu='http://schemas.xmlsoap.org/ws/2002/12/utility'>
             <wsse:BinarySecurityToken valueType='String' EncodingType='wsse:Base64Binary'>""" \
        + secToken \
        + """</wsse:BinarySecurityToken>
          </wsse:Security>
       </SOAP-ENV:Header>
       <SOAP-ENV:Body>
          <eTicketCouponRQ xmlns="http://webservices.sabre.com/sabreXML/2011/10" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="2.0.0">
            <Ticketing eTicketNumber='""" \
        + doc_no \
        + """'/>
        </eTicketCouponRQ>
       </SOAP-ENV:Body>
    </SOAP-ENV:Envelope> """
    response = requests.post(url, data=body, headers=headers)
    myprint('ticket/' + doc_no, response.content)
    print 'eTicket Retrieved ...'

    return response.content


def queue_count(queue_number, secToken):
    log()
    body = \
        """
<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:eb='http://www.ebxml.org/namespaces/messageHeader' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/1999/XMLSchema'>
       <SOAP-ENV:Header>
          <eb:MessageHeader SOAP-ENV:mustUnderstand='1' eb:version='1.0'>
             <eb:From>
                <eb:PartyId type='urn:x12.org:IO5:01'>999999</eb:PartyId>
             </eb:From>
             <eb:To>
                <eb:PartyId type='urn:x12.org:IO5:01'>123123</eb:PartyId>
             </eb:To>
             <eb:CPAId>6B3D</eb:CPAId>
             <eb:ConversationId>TEST-6B3D</eb:ConversationId>
             <eb:Service eb:type='OTA'>QueueCountLLSRQ</eb:Service>
             <eb:Action>QueueCountLLSRQ</eb:Action>
             <eb:MessageData>
                <eb:MessageId>170390</eb:MessageId>
                <eb:Timestamp>2012-06-07T10:00:00</eb:Timestamp>
                <eb:TimeToLive>2013-06-06T23:59:59</eb:TimeToLive>
             </eb:MessageData>
          </eb:MessageHeader>
          <wsse:Security xmlns:wsse='http://schemas.xmlsoap.org/ws/2002/12/secext' xmlns:wsu='http://schemas.xmlsoap.org/ws/2002/12/utility'>
             <wsse:BinarySecurityToken valueType='String' EncodingType='wsse:Base64Binary'>""" \
        + secToken \
        + """</wsse:BinarySecurityToken>
          </wsse:Security>
       </SOAP-ENV:Header>
       <SOAP-ENV:Body>
           <QueueCountRQ xmlns='http://webservices.sabre.com/sabreXML/2011/10' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' Version='2.2.0'>
<QueueInfo>
<QueueIdentifier Number='""" \
        + queue_number \
        + """' PseudoCityCode='6B3D'/>
</QueueInfo>
</QueueCountRQ>
       </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
"""
    response = requests.post(url, data=body, headers=headers)
    print 'Queue Count Done'
    myprint('QC/' + str(datetime.datetime.now()), response.content)
    return response.content


def queue_access(queue_number, secToken,pccToEmulate):
    log()
    body = \
        """
<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:eb='http://www.ebxml.org/namespaces/messageHeader' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/1999/XMLSchema'>
       <SOAP-ENV:Header>
          <eb:MessageHeader SOAP-ENV:mustUnderstand='1' eb:version='1.0'>
             <eb:From>
                <eb:PartyId type='urn:x12.org:IO5:01'>999999</eb:PartyId>
             </eb:From>
             <eb:To>
                <eb:PartyId type='urn:x12.org:IO5:01'>123123</eb:PartyId>
             </eb:To>
             <eb:CPAId>6B3D</eb:CPAId>
             <eb:ConversationId>TEST-6B3D</eb:ConversationId>
             <eb:Service eb:type='OTA'>QueueAccessLLSRQ</eb:Service>
             <eb:Action>QueueAccessLLSRQ</eb:Action>
             <eb:MessageData>
                <eb:MessageId>170390</eb:MessageId>
                <eb:Timestamp>2012-06-07T10:00:00</eb:Timestamp>
                <eb:TimeToLive>2013-06-06T23:59:59</eb:TimeToLive>
             </eb:MessageData>
          </eb:MessageHeader>
          <wsse:Security xmlns:wsse='http://schemas.xmlsoap.org/ws/2002/12/secext' xmlns:wsu='http://schemas.xmlsoap.org/ws/2002/12/utility'>
             <wsse:BinarySecurityToken valueType='String' EncodingType='wsse:Base64Binary'>""" \
        + secToken \
        + """</wsse:BinarySecurityToken>
          </wsse:Security>
       </SOAP-ENV:Header>
       <SOAP-ENV:Body>
       <QueueAccessRQ xmlns='http://webservices.sabre.com/sabreXML/2011/10' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' Version='2.0.7'>
            <QueueIdentifier Number='""" \
        + queue_number \
        + """' PseudoCityCode='"""+pccToEmulate+"""'>
                <List Ind="true"/>
            </QueueIdentifier>
        </QueueAccessRQ>
       </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
"""
    response = requests.post(url, data=body, headers=headers)

    # print response.content;

    print 'Queue Access Done'
    myprint('qa/' + str(datetime.datetime.now()), response.content)
    return response.content


def pnr_get(pnr):
    log()
    t = start_session(pccToEmulate)
    x = get_pnr(pnr, t, 'test')
    stop_session(t)
    return x


def get_pnr(pnr, secToken, filename):
    log()
    body = \
        """
<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:eb='http://www.ebxml.org/namespaces/messageHeader' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/1999/XMLSchema'>
       <SOAP-ENV:Header>
          <eb:MessageHeader SOAP-ENV:mustUnderstand='1' eb:version='1.0'>
             <eb:From>
                <eb:PartyId type='urn:x12.org:IO5:01'>999999</eb:PartyId>
             </eb:From>
             <eb:To>
                <eb:PartyId type='urn:x12.org:IO5:01'>123123</eb:PartyId>
             </eb:To>
             <eb:CPAId>6B3D</eb:CPAId>
             <eb:ConversationId>TEST-6B3D</eb:ConversationId>
             <eb:Service eb:type='OTA'>TravelItineraryReadRQ</eb:Service>
             <eb:Action>TravelItineraryReadRQ</eb:Action>
             <eb:MessageData>
                <eb:MessageId>170390</eb:MessageId>
                <eb:Timestamp>2012-06-07T10:00:00</eb:Timestamp>
                <eb:TimeToLive>2013-06-06T23:59:59</eb:TimeToLive>
             </eb:MessageData>
          </eb:MessageHeader>
          <wsse:Security xmlns:wsse='http://schemas.xmlsoap.org/ws/2002/12/secext' xmlns:wsu='http://schemas.xmlsoap.org/ws/2002/12/utility'>
             <wsse:BinarySecurityToken valueType='String' EncodingType='wsse:Base64Binary'>""" \
        + secToken \
        + """</wsse:BinarySecurityToken>
          </wsse:Security>
       </SOAP-ENV:Header>
       <SOAP-ENV:Body>
            <TravelItineraryReadRQ xmlns='http://services.sabre.com/res/tir/v3_8' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' TimeStamp='2014-12-16T16:00:00-06:00' Version='3.8.0'>
                <MessagingDetails>
                    <SubjectAreas>
                        <SubjectArea>FULL</SubjectArea>
                    </SubjectAreas>
                </MessagingDetails>
                <UniqueID ID='""" \
        + pnr \
        + """'/>
                <ReturnOptions UnmaskCreditCard='false'/>
            </TravelItineraryReadRQ>
       </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
"""
    response = requests.post(url, data=body, headers=headers)

    # print response.content;

    myprint('tir/' + filename, response.content)

    print 'Itinerary Read Done'
    return response.content


def get_price(secToken, filename):
    log()
    body = \
        """
<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:eb='http://www.ebxml.org/namespaces/messageHeader' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/1999/XMLSchema'>
       <SOAP-ENV:Header>
          <eb:MessageHeader SOAP-ENV:mustUnderstand='1' eb:version='1.0'>
             <eb:From>
                <eb:PartyId type='urn:x12.org:IO5:01'>999999</eb:PartyId>
             </eb:From>
             <eb:To>
                <eb:PartyId type='urn:x12.org:IO5:01'>123123</eb:PartyId>
             </eb:To>
             <eb:CPAId>6B3D</eb:CPAId>
             <eb:ConversationId>TEST-6B3D</eb:ConversationId>
             <eb:Service eb:type='OTA'>DisplayPriceQuoteLLSRQ</eb:Service>
             <eb:Action>DisplayPriceQuoteLLSRQ</eb:Action>
             <eb:MessageData>
                <eb:MessageId>170390</eb:MessageId>
                <eb:Timestamp>2012-06-07T10:00:00</eb:Timestamp>
                <eb:TimeToLive>2013-06-06T23:59:59</eb:TimeToLive>
             </eb:MessageData>
          </eb:MessageHeader>
          <wsse:Security xmlns:wsse='http://schemas.xmlsoap.org/ws/2002/12/secext' xmlns:wsu='http://schemas.xmlsoap.org/ws/2002/12/utility'>
             <wsse:BinarySecurityToken valueType='String' EncodingType='wsse:Base64Binary'>""" \
        + secToken \
        + """</wsse:BinarySecurityToken>
          </wsse:Security>
       </SOAP-ENV:Header>
       <SOAP-ENV:Body>
            <DisplayPriceQuoteRQ xmlns="http://webservices.sabre.com/sabreXML/2011/10" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="2.5.0">
                <AirItineraryPricingInfo>
                    <Record/>
                </AirItineraryPricingInfo>
            </DisplayPriceQuoteRQ>
       </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
"""
    response = requests.post(url, data=body, headers=headers)

    # print response.content;

    print 'PriceQuote Done'
    myprint('pq/PQ_' + filename, response.content)
    return response.content


def get_airline_details(airline_code, flight_number, dt):
    log()
    t = start_session(pccToEmulate)
    body = \
        """ <SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:eb='http://www.ebxml.org/namespaces/messageHeader' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/1999/XMLSchema'>
           <SOAP-ENV:Header>
              <eb:MessageHeader SOAP-ENV:mustUnderstand='1' eb:version='2.0'>
                 <eb:From>
                    <eb:PartyId type='urn:x12.org:IO5:01'>1212</eb:PartyId>
                 </eb:From>
                 <eb:To>
                    <eb:PartyId type='urn:x12.org:IO5:01'>2323</eb:PartyId>
                 </eb:To>
                 <eb:CPAId>6B3D</eb:CPAId>
                 <eb:ConversationId>TEST-6B3D</eb:ConversationId>
                 <eb:Service eb:type='OTA'>OTA_AirFlifoLLSRQ</eb:Service>
                 <eb:Action>OTA_AirFlifoLLSRQ</eb:Action>
                 <eb:MessageData>
                    <eb:MessageId>1001</eb:MessageId>
                    <eb:Timestamp>2012-06-07T10:00:01</eb:Timestamp>
                    <eb:TimeToLive>2013-06-06T23:59:59</eb:TimeToLive>
                 </eb:MessageData>
              </eb:MessageHeader>
              <wsse:Security xmlns:wsse='http://schemas.xmlsoap.org/ws/2002/12/secext' xmlns:wsu='http://schemas.xmlsoap.org/ws/2002/12/utility'>
                 <wsse:BinarySecurityToken valueType='String' EncodingType='wsse:Base64Binary'>""" \
        + t \
        + """</wsse:BinarySecurityToken>
              </wsse:Security>
           </SOAP-ENV:Header>
           <SOAP-ENV:Body>
           <OTA_AirFlifoRQ xmlns='http://webservices.sabre.com/sabreXML/2011/10' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' Version='2.0.0'>
<OriginDestinationInformation>
<FlightSegment DepartureDateTime='""" \
        + dt + """' FlightNumber='""" + flight_number \
        + """'>
<MarketingAirline Code='""" + airline_code \
        + """' FlightNumber='""" + flight_number \
        + """'/>
</FlightSegment>
</OriginDestinationInformation>
</OTA_AirFlifoRQ>

           </SOAP-ENV:Body>
        </SOAP-ENV:Envelope> """

    response = requests.post(url, data=body, headers=headers)
    stop_session(t)
    r = etree.XML(body)

    # print etree.tostring(r)
    # myprint(response.content);

    root = etree.XML(response.content)
    x = root[-1][-1]
    flightinfo = x[-1]
    scheduledinfo = flightinfo[0]
    origin = scheduledinfo[0]
    destination = scheduledinfo[1]
    o = origin.get('LocationCode')
    d = destination.get('LocationCode')
    dep_time = origin[0].get('Scheduled')
    arr_time = destination[0].get('Scheduled')

    return [o, d, dep_time, arr_time]


current_time = ''


def alternate_fare(stt, pnr):
    log()
    t = start_session(pccToEmulate)
    body = \
        """<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:eb='http://www.ebxml.org/namespaces/messageHeader' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/1999/XMLSchema'>
               <SOAP-ENV:Header>
                  <eb:MessageHeader SOAP-ENV:mustUnderstand='1' eb:version='2.0'>
                     <eb:From>
                        <eb:PartyId type='urn:x12.org:IO5:01'>1212</eb:PartyId>
                     </eb:From>
                     <eb:To>
                        <eb:PartyId type='urn:x12.org:IO5:01'>2323</eb:PartyId>
                     </eb:To>
                     <eb:CPAId>6B3D</eb:CPAId>
                     <eb:ConversationId>TEST-6B3D</eb:ConversationId>
                     <eb:Service eb:type='OTA'>SabreCommandLLSRQ</eb:Service>
                     <eb:Action>SabreCommandLLSRQ</eb:Action>
                     <eb:MessageData>
                        <eb:MessageId>1001</eb:MessageId>
                        <eb:Timestamp>2012-06-07T10:00:01</eb:Timestamp>
                        <eb:TimeToLive>2013-06-06T23:59:59</eb:TimeToLive>
                     </eb:MessageData>
                  </eb:MessageHeader>
                  <wsse:Security xmlns:wsse='http://schemas.xmlsoap.org/ws/2002/12/secext'
                   xmlns:wsu='http://schemas.xmlsoap.org/ws/2002/12/utility'>
                     <wsse:BinarySecurityToken valueType='String' EncodingType='wsse:Base64Binary'>""" \
        + t \
        + """</wsse:BinarySecurityToken>
                  </wsse:Security>
               </SOAP-ENV:Header>
        <SOAP-ENV:Body><SabreCommandLLSRQ xmlns='http://webservices.sabre.com/sabreXML/2003/07'
        xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        TimeStamp='2014-03-04T14:00:00' Version='1.8.1'>
            <Request Output='SCREEN' CDATA='true'>
                <HostCommand>""" \
        + str(stt) \
        + """</HostCommand></Request>
                </SabreCommandLLSRQ>
                </SOAP-ENV:Body>
                </SOAP-ENV:Envelope> """
    print 'Ding'
    response = requests.post(url, data=body, headers=headers)
    stop_session(t)
    root = etree.XML(response.content)
    y = root[-1][-1][0]
    print etree.tostring(y, pretty_print=True)
    x = etree.tostring(y, pretty_print=True)
    parts = x.split('ITINERARY OPTION ')
    myprint('alt/ALT_' + pnr, x)
    results = []
    for part in parts[1:]:
        ps = part.split('\n')
        ps.reverse()
        fareid = 'Fare ' + str(ps.pop())
        result = []
        check = 0
        while ps != []:
            segment = ps.pop()
            infos = segment.split()
            infos.reverse()
            fare = ''
            currency = ''
            try:
                checkk = infos.pop()
                print checkk
                if checkk == 'TOTAL':
                    t_fare = infos[0]
                    t_currency = infos[1]
                elif checkk.isdigit():
                    marketing_airline_code = infos.pop()
                    if len(infos) == 13:
                        op_airline_code = infos.pop()
                    flight_number = infos.pop()
                    rbd = infos.pop()
                    dep_date = m_date(infos.pop())
                    day_week = infos.pop()
                    origin = infos.pop()
                    destination = infos.pop()
                    dep_time = infos.pop()
                    arr_time = infos.pop()
                    equipment = infos.pop()
                    stopover = infos.pop()
                    fare_basis = ''
                    result.append([
                        marketing_airline_code,
                        origin,
                        destination,
                        currency,
                        fare,
                        pnr,
                        flight_number,
                        rbd,
                        dep_date,
                        fare_basis,
                        dep_time,
                        arr_time,
                        fareid,
                    ])
                else:
                    continue
            except:

                # pdb.set_trace()

                continue
        try:
            result[0][4] = t_fare
            result[0][3] = t_currency
            results.append(result)
        except:
            pass
    return results


# def commit_alt_fare(
#     tktnumber,
#     timestamp,
#     gds_source,
#     marketing_airline_code,
#     origin,
#     destination,
#     currency,
#     fare,
#     pnr,
#     flight_number,
#     rbd,
#     dep_date,
#     fare_basis,
#     dep_time,
#     arr_time,
#     fareid,
#     depdatetime
# ):

#     try:
#         cnx = mysql.connector.connect(user='rt_bot', password='mp.work.',
#                                       host='tripnomicsdb.cloudapp.net',
#                                       database='Alternatefare')
#         cursor = cnx.cursor();cnx.autocommit = True
#         add_gen_row = 'INSERT INTO Fare_Details ' + 'VALUES(' + '%s,' \
#             * 21 + '%s)'
#         gen_info_insert = tuple([
#             tktnumber,
#             timestamp,
#             gds_source,
#             marketing_airline_code,
#             origin,
#             destination,
#             currency,
#             '',
#             fare,
#             pnr,
#             flight_number,
#             rbd,
#             dep_date,
#             fare_basis,
#             dep_time,
#             arr_time,
#             fareid,
#             '',
#             '',
#             '','',depdatetime
#         ])
#         cursor.execute(add_gen_row, gen_info_insert)
#         cnx.commit()
#         cursor.close()
#         cnx.close()
#         print "Committed"
#     except Exception,e:
#         print e
#         print "ERROR !!!!!! Can't commit alternate fare to database"
#         return False
#     return True


# def components(xml_body, preferred_airlines,pnr,pccToEmulate):
#     dts, orgs,dstns, rbds, indicators = [],[],[],[],[]
#     root = etree.XML(xml_body)
#     y = root[-1][-1]
#     ns = y.nsmap
#     flight_segments = y.findall(
#         './/tir38:ReservationItems/tir38:Item/tir38:FlightSegment', ns)
#     result = []
#     for flight_segment in flight_segments:
#         try:
#             connectionInd = flight_segment.get('ConnectionInd')
#         except:
#             connectionInd = 'O'
#         if connectionInd is None:
#             connectionInd = 'O'
#         try:
#             rbd = flight_segment.get('ResBookDesigCode')
#         except:
#             rbd = 'Y'
#         dep_date = flight_segment.get('DepartureDateTime')
#         origin = flight_segment.find('.//tir38:OriginLocation',
#                                      ns).get('LocationCode')
#         destination = flight_segment.find(
#             './/tir38:DestinationLocation',
#             ns).get('LocationCode')
#         depdate = datetime.datetime.strptime(dep_date, '%Y-%m-%dT%H:%M')
#         depdate = depdate.strftime('%Y-%m-%dT%H:%M:%S')
#         orgs.append(origin)
#         dstns.append(destination)
#         dts.append(depdate)
#         rbds.append(rbd)
#         indicators.append(connectionInd)
#     altstring = altfare(dts,[orgs,dstns],rbds,pnr,indicators,pccToEmulate)
#     return altstring

# def class_of_booking(rbd):
#     cnx = mysql.connector.connect(user='rt_bot', password='mp.work.',
#                                   host='tripnomicsdb.cloudapp.net',
#                                   database='PNR_Trigger')
#     cursor = cnx.cursor();cnx.autocommit = True
#     try:
#         select_stmt = \
#             """ select if(count(*)=0,'Economy',CabinClass)
#             FROM Masters.Cabin_Class_Mapping where FareClass like CONCAT('%',%(fare_class)s,'%') """
#         cursor.execute(select_stmt, {'fare_class': rbd})
#         row = cursor.fetchone()
#         print row
#         cclass = row[0]
#     except:
#         cclass = 'Economy'

#     cursor.close()
#     cnx.close()
#     return cclass


# def pref_airlines(customer_code, origin, destination):
#     return []

# def make_body(dates, dests, rbd, indicators):
#     dd = []
#     indicators.append("O")
#     oo = []
#     dts = []
#     x = []
#     # ###print pnr+" LOG ", "Destinations",dests
#     origins = dests[0]
#     # ###print pnr+" LOG ", "Origins",origins
#     destinations = dests[1]
#     mmaster = indicators
#     origin_indicators = mmaster[:-1]
#     destination_indicators = mmaster[1:]

#     for i in range(len(destinations)):
#         if origin_indicators[i] == "O":
#             oo.append(origins[i])
#         if destination_indicators[i] == "O":
#             dd.append(destinations[i])

#     for i in range(len(destinations)):
#         if indicators[i] == "O":
#             # ###print pnr+" LOG ", i, len(dates)
#             dts.append(dates[i])

#     # destinations = dd
#     dates = dts
#     # ###print pnr+" LOG ", "RBD"
#     # ###print pnr+" LOG ", rbd
#     ###print len(oo), len(dd), len(dates), len(rbd)
#     for i in range(len(oo)):
#         x.append([oo[i], dd[i], dates[i], rbd[i]])
#     ###print len(x),x
#     # destinations = dd
#     dates = dts
#     # ###print pnr+" LOG ", "RBD"
#     # ###print pnr+" LOG ", rbd

#     t = ""
#     ###print "Legs ",len(x)
#     for i in range(len(x)):
#         dt = x[i][2]
#         o = x[i][0]
#         d = x[i][1]
#         booking_class = class_of_booking(x[i][3])
#         # ###print pnr+" LOG ", booking_class
#         if 'ECONOMY' in booking_class.upper():
#             rd = "Y"
#         elif 'BUSINESS' in booking_class.upper():
#             rd = "J"
#         else:
#             rd = "F"
#         t = t + """<OriginDestinationInformation RPH ='""" + str(i + 1) + """'>
#         <DepartureDateTime>""" + dt + """</DepartureDateTime>
#         <OriginLocation LocationCode='""" + o + """' />
#         <DestinationLocation LocationCode ='""" + d + """' />
#         <TPA_Extensions>"""+"""<CabinPref PreferLevel='Preferred' Cabin='""" + rd + """'/>
#         </TPA_Extensions>
#     </OriginDestinationInformation >"""
#     # ###print pnr+" LOG ", t
#     return t

# def altfare(dt, o, rbd, pnr, indicators,pccToEmulate):

#     x = """<SOAP-ENV:Body><OTA_AirLowFareSearchRQ xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns='http://www.opentravel.org/OTA/2003/05' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' Target='Production' Version='3.0.0' ResponseType='OTA' ResponseVersion='3.0.0' AvailableFlightsOnly="true">
#         <POS>
#             <Source PseudoCityCode='6B3D'>
#                 <RequestorID ID='1' Type='1'>
#                     <CompanyName Code='TN'/>
#                 </RequestorID>
#             </Source>
#         </POS>
#         """ + make_body(dt, o, rbd, indicators) + """
# 	<TravelPreferences ValidInterlineTicket='false' MaxStopsQuantity='0' Hybrid='true'></TravelPreferences>
#         <TravelerInfoSummary>
#             <SeatsRequested>1</SeatsRequested>
#             <AirTravelerAvail>
#                 <PassengerTypeQuantity Code='ADT' Quantity='1'/>
#             </AirTravelerAvail>
#         </TravelerInfoSummary>
#         <TPA_Extensions>
#             <IntelliSellTransaction>
#                 <RequestType Name='200ITINS'/>
#             </IntelliSellTransaction>
#         </TPA_Extensions>
#     </OTA_AirLowFareSearchRQ></SOAP-ENV:Body>"""
#     t = start_session(pccToEmulate)
#     body = """ <SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:eb='http://www.ebxml.org/namespaces/messageHeader' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/1999/XMLSchema'>
#            <SOAP-ENV:Header>
#               <eb:MessageHeader SOAP-ENV:mustUnderstand='1' eb:version='2.0'>
#                  <eb:From>
#                     <eb:PartyId type='urn:x12.org:IO5:01'>1212</eb:PartyId>
#                  </eb:From>
#                  <eb:To>
#                     <eb:PartyId type='urn:x12.org:IO5:01'>2323</eb:PartyId>
#                  </eb:To>
#                  <eb:CPAId>6B3D</eb:CPAId>
#                  <eb:ConversationId>TEST-6B3D</eb:ConversationId>
#                  <eb:Service eb:type='OTA'>BargainFinderMaxRQ</eb:Service>
#                  <eb:Action>BargainFinderMaxRQ</eb:Action>
#                  <eb:MessageData>
#                     <eb:MessageId>1001</eb:MessageId>
#                     <eb:Timestamp>2012-06-07T10:00:01</eb:Timestamp>
#                     <eb:TimeToLive>2013-06-06T23:59:59</eb:TimeToLive>
#                  </eb:MessageData>
#               </eb:MessageHeader>
#               <wsse:Security xmlns:wsse='http://schemas.xmlsoap.org/ws/2002/12/secext' xmlns:wsu='http://schemas.xmlsoap.org/ws/2002/12/utility'>
#                  <wsse:BinarySecurityToken valueType='String' EncodingType='wsse:Base64Binary'>""" + \
#         t + """</wsse:BinarySecurityToken>
#               </wsse:Security>
#            </SOAP-ENV:Header>
#            """ + x + """
#         </SOAP-ENV:Envelope> """
#     # ###print pnr+" LOG ", "#" * 80
#     response = requests.post(url, data=body, headers=headers)
#     stop_session(t)
#     return response.content


# def move_pnr(pnr,pccToMove,pccFrom,DestinationQueue,OriginQueue):
#     secToken = start_session(pccFrom)
#     body = \
#         """ <SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:eb='http://www.ebxml.org/namespaces/messageHeader' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/1999/XMLSchema'>
#        <SOAP-ENV:Header>
#           <eb:MessageHeader SOAP-ENV:mustUnderstand='1' eb:version='2.0'>
#              <eb:From>
#                 <eb:PartyId type='urn:x12.org:IO5:01'>1212</eb:PartyId>
#              </eb:From>
#              <eb:To>
#                 <eb:PartyId type='urn:x12.org:IO5:01'>2323</eb:PartyId>
#              </eb:To>
#              <eb:CPAId>6B3D</eb:CPAId>
#              <eb:ConversationId>TEST-6B3D</eb:ConversationId>
#              <eb:Service eb:type='OTA'>QueueMoveLLSRQ</eb:Service>
#              <eb:Action>QueueMoveLLSRQ</eb:Action>
#              <eb:MessageData>
#                 <eb:MessageId>1001</eb:MessageId>
#                 <eb:Timestamp>2012-06-07T10:00:01</eb:Timestamp>
#                 <eb:TimeToLive>2013-06-06T23:59:59</eb:TimeToLive>
#              </eb:MessageData>
#           </eb:MessageHeader>
#           <wsse:Security xmlns:wsse='http://schemas.xmlsoap.org/ws/2002/12/secext' xmlns:wsu='http://schemas.xmlsoap.org/ws/2002/12/utility'>
#              <wsse:BinarySecurityToken valueType='String' EncodingType='wsse:Base64Binary'>""" \
#         + secToken \
#         + """</wsse:BinarySecurityToken>
#           </wsse:Security>
#        </SOAP-ENV:Header>
#        <SOAP-ENV:Body>
#             <QueueMoveRQ xmlns="http://webservices.sabre.com/sabreXML/2011/10" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="2.0.0">
#                 <QueueInfo>
#                     <DestinationQueue>
#                         <QueueIdentifier Number='"""+DestinationQueue+"""' PseudoCityCode='"""+pccToMove+"""'/>
#                     </DestinationQueue>
#                     <OriginQueue>
#                         <QueueIdentifier Number='"""+OriginQueue+"""' PseudoCityCode='"""+pccFrom+"""'/>
#                     </OriginQueue>
#                 </QueueInfo>
#             </QueueMoveRQ>
#        </SOAP-ENV:Body>
#     </SOAP-ENV:Envelope> """
#     response = requests.post(url, data=body, headers=headers)
#     stop_session(secToken)
#     print "Moved PNR",pnr,pccToMove,DestinationQueue
#     # print response.content

#     return response.content

