from defs import *
import json
from pprint import pprint
from lxml import etree

import requests

d = dict()


def requestBody(datesofdeparture, timewindows, departures, arrivals, cabinList):
    body = ""

    for index in range(len(datesofdeparture)):
        departuredatetime = datesofdeparture[index]
        departurewindow = timewindows[index]
        departure = departures[index]
        arrival = arrivals[index]
        cabin = cabinList[index]
        if 'ECONOMY' in cabin.upper():
            rd = "Y"
        elif 'BUSINESS' in cabin.upper():
            rd = "J"
        else:
            rd = "F"
        cabin = rd
        # <DepartureWindow>""" + departurewindow + """</DepartureWindow>
        body += """<OriginDestinationInformation RPH ='""" + str(index + 1) + """'>
                    <DepartureDateTime>""" + departuredatetime + """</DepartureDateTime>
                    
                    <OriginLocation LocationCode='""" + departure + """' />
                    <DestinationLocation LocationCode ='""" + arrival + """' />
                    <TPA_Extensions>
                        <AlternateTime PlusMinus='"""+departurewindow+"""'/>
                        <CabinPref PreferLevel='Preferred' Cabin='""" + cabin + """'/>
                    </TPA_Extensions>
                </OriginDestinationInformation >
        """
    return body


def commit_alt_fare(tktnumber,
                    pnr,
                    timestamp, origin, destination, dep_date, marketing_airline_code, flight_number, dep_time, arr_time, fare, fare_basis, rbd, org, dest, fid, ddt, orderby):
    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(
            `TktNumber`,
            `PNR`,
            `Timestamp`,
            `GDS_Source`,
            `Origin`,
            `Destination`,
            `DateOfJourney`,
            `Airline`,
            `FlightNo`,
            `DepartureTime`,
            `ArrivalTime`,
            `Fare`,
            `FareBasis`,
            `FareClass`,
            `FareID`,
            `Dep_Date`
            ) """ + 'VALUES(' + '%s,' \
            * 15 + '%s)'
        gen_info_insert = tuple([
            tktnumber,
            pnr,
            timestamp,
            '1S',
            origin,
            destination,
            dep_date,
            marketing_airline_code,
            flight_number,
            dep_time,
            arr_time,
            fare,
            fare_basis,
            rbd,
            fid,
            ddt
        ])
        # if ((org == origin)&(dest == destination)):
        cursor.execute(add_gen_row, gen_info_insert)
        cnx.commit()
        # print "Committed"
        # else:
        #     print org + " " + dest + " vs " + origin + destination
        print cursor.statement
        cursor.close()
        cnx.close()

    except Exception, e:
        print e
        print "ERROR !!!!!! Can't commit alternate fare to database"
        return False
    return True


def file_Fare(pnr,tktnumber,datesofdeparture, timewindows, departures, arrivals, cabinList,faredrop = False,paxNumber=1):
    t = start_session()
    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><SOAP-ENV:Body>
            
    <OTA_AirLowFareSearchRQ
            xmlns='http://www.opentravel.org/OTA/2003/05'
            ResponseType='OTA'
            ResponseVersion='4.1.0'
            Version='4.1.0'
            AvailableFlightsOnly='true'>
            <POS>
                <Source PseudoCityCode='6B3D'>
                    <RequestorID ID='1' Type='1'>
                        <CompanyName Code='TN'/>
                    </RequestorID>
                </Source>
            </POS>
            """ + requestBody(datesofdeparture, timewindows, departures, arrivals, cabinList) + """
            
            <TravelPreferences
                ETicketDesired='true'
                ValidInterlineTicket='true'
                MaxStopsQuantity='1'
                Hybrid='true'
                LookForAlternatives='true'>            
            </TravelPreferences>
            <TravelerInfoSummary>
                <SeatsRequested>1</SeatsRequested>
                <AirTravelerAvail>
                    <PassengerTypeQuantity Code='ADT' Quantity='"""+str(paxNumber)+"""'/>
                </AirTravelerAvail>
            </TravelerInfoSummary>
            <TPA_Extensions>
                <IntelliSellTransaction>
                    <RequestType Name='100ITINS'/>
                    <ResponseSorting SortFaresInsideItin='true'/>
                </IntelliSellTransaction>
            </TPA_Extensions>
        </OTA_AirLowFareSearchRQ>

        </SOAP-ENV:Body></SOAP-ENV:Envelope> """
    # print pnr+" LOG ", "#" * 80
    response = requests.post(url, data=body, headers=headers)
    print response.content

    stop_session(t)

    import xml.dom.minidom

    xml = xml.dom.minidom.parseString(response.content)
    pretty_xml_as_string = xml.toprettyxml()
    print pretty_xml_as_string

    root = etree.XML(response.content)
    y = root[-1][-1]
    ns = y.nsmap
    # ###print pnr+" LOG ", ns
    ns.pop(None)
    # ns['ddd'] = ns['None']
    ns['ddd'] = "http://www.opentravel.org/OTA/2003/05"
    # print pnr+" LOG ", etree.tostring(y, pretty_print=True)
    # ###print pnr+" LOG ", "#" * 80
    PricedItineraries = y.xpath(".//ddd:PricedItinerary", namespaces=ns)

    # keyword =  o[0][0]+ "".join(o[1])
    ddt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    org = ""
    dest = ""
    for priceditinerary in PricedItineraries[:10]:
        orderby = priceditinerary.get("SequenceNumber")
        flightsegments = priceditinerary.xpath(
            ".//ddd:FlightSegment", namespaces=ns)
        fid = "Fare " + str(orderby)
        for flightsegment in flightsegments:
            # print pnr+" LOG ", "#" * 80
            timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            marketing_airline_code = flightsegment.xpath(
                ".//ddd:MarketingAirline", namespaces=ns)[0].get("Code")
            origin = flightsegment.xpath(
                ".//ddd:DepartureAirport",
                namespaces=ns)[0].get("LocationCode")
            destination = flightsegment.xpath(
                ".//ddd:ArrivalAirport",
                namespaces=ns)[0].get("LocationCode")
            currency = priceditinerary.xpath(
                ".//ddd:ItinTotalFare//ddd:BaseFare",
                namespaces=ns)[0].get("CurrencyCode")
            fare = priceditinerary.xpath(
                ".//ddd:ItinTotalFare//ddd:TotalFare",
                namespaces=ns)[0].get("Amount")
            flight_number = flightsegment.get("FlightNumber")
            rbd = flightsegment.get("ResBookDesigCode")
            dep_date = flightsegment.get("DepartureDateTime")
            depdate = datetime.datetime.strptime(dep_date, '%Y-%m-%dT%H:%M:%S')
            dep_date = depdate.strftime('%Y-%m-%d')
            dep_time = depdate.strftime('%H%M')
            arr_time = flightsegment.get("ArrivalDateTime")
            arrdate = datetime.datetime.strptime(arr_time, '%Y-%m-%dT%H:%M:%S')
            arr_time = arrdate.strftime('%H%M')

            fare_basis = priceditinerary.xpath(
                ".//ddd:FareCalcLine", namespaces=ns)[0].get("Info")
            depdatetime = dep_date + " " + dep_time
            depdatetime = datetime.datetime.strptime(
                depdatetime, "%Y-%m-%d %H%M")
            depdatetime = depdatetime.strftime("%Y-%m-%d %H:%M:%S")
            if (faredrop) :
                fid = depdatetime
            
            commit_alt_fare(tktnumber,
                            pnr,
                            timestamp, origin, destination, dep_date, marketing_airline_code,
                            flight_number, dep_time, arr_time, fare, fare_basis, rbd, org, dest, fid, ddt, orderby)
