import os
import sys
from flask import Flask, request, jsonify
from flask import url_for, redirect, send_from_directory
from flask import make_response, abort
import requests
import json

from angular_flask import app

# routing for basic pages (pass routing onto the Angular app)
@app.route('/')
def basic_pages(**kwargs):
    return make_response(open('angular_flask/templates/index.html').read())

# https://api.sandbox.amadeus.com/v1.2/flights/inspiration-search?apikey=NhFsGHrLaDhgJSOJNO8QdiGQ1DQdEnjm&origin=BLR
@app.route('/insp_search')
def insp_search():
    origin = request.args.get('origin')
    print >> sys.stderr, "origin = {origin}".format(origin = origin)
    search_url = ("https://api.sandbox.amadeus.com/v1.2/flights/inspiration-search?apikey=NhFsGHrLaDhgJSOJNO8QdiGQ1DQdEnjm&origin={origin}"
        .format(origin = origin))
    call_response = (requests.get(search_url)).json()
    call_response["iata_map"] = {}

    cur_dir = os.path.dirname(__file__)
    rel_air_dict = os.path.join(cur_dir, "../data/airports.json")

    with open(rel_air_dict) as data:
        iata_dict = json.load(data)

    for flight in call_response["results"]:
        try:
            latlong = [iata_dict[flight['destination']]['latitude'], iata_dict[flight['destination']]['longitude']]
            call_response['iata_map'][flight['destination']] = latlong
        except KeyError as e:
            latlong = ['null', 'null']
            call_response['iata_map'][flight['destination']] = latlong


    return jsonify(call_response)

# special file handlers and error handlers
@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'img/favicon.ico')

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404
