#!/usr/bin/env python

from flask import Flask, make_response
import sys
import os


app = Flask(__name__)
sys.stdout = sys.stderr
TILES = {}


@app.route('/pano/<mds_key>/<tile_coords>', methods=['GET'])
def get_pano(mds_key, tile_coords):
    global TILES
    if tile_coords not in TILES:
        return make_response('', 404)
    return make_response(TILES[tile_coords], 200)


@app.route('/ping')
def ping():
    return ''


def main(argv=sys.argv):
    # Make flask to use HTTP/1.1 protocol (to support Keep Alive connections)
    from BaseHTTPServer import BaseHTTPRequestHandler
    BaseHTTPRequestHandler.protocol_version = 'HTTP/1.1'

    global TILES
    TILES_DIR = sys.argv[3]
    for tile_coords in os.listdir(sys.argv[3]):
        with open(os.path.join(TILES_DIR, tile_coords), mode='rb') as tile:
            TILES[tile_coords] = tile.read()

    app.run(sys.argv[1], sys.argv[2])


if __name__ == "__main__":
    main()
