from flask import Flask, Response, request, send_from_directory
from flask_cors import CORS 
from urllib.parse import urlparse
import sys, requests

app = Flask(__name__)

DATA_PATH = sys.argv[1]
COUCHDB_PROTO = 'http' 
COUCHDB_PORT = '5984'
DB = 'vl_db'

app = Flask(__name__, static_url_path='')
app.url_map.strict_slashes = False
CORS(app)

## =================== URLs to the Web Apps ======================
@app.route('/<fn>', methods=['GET'])
def html(fn):
    app.logger.debug('hit html folder: ' + fn)
    return send_from_directory(DATA_PATH + '/web-apps', fn)

@app.route('/js/<path:fn>', methods=['GET'])
def js(fn):
    app.logger.debug('hit js folder: ' + fn)
    return send_from_directory(DATA_PATH + '/web-apps/js', fn)

@app.route('/css/<fn>', methods=['GET'])
def css(fn):
    app.logger.debug('hit css folder: ' + fn)
    return send_from_directory(DATA_PATH + '/web-apps/css', fn)

@app.route('/img/<fn>', methods=['GET'])
def img(fn):
    app.logger.debug('hit img folder: ' + fn)
    return send_from_directory(DATA_PATH + '/web-apps/img', fn)

@app.route('/lib/<path:fn>', methods=['GET'])
def lib(fn):
    app.logger.debug('hit lib folder: ' + fn)
    return send_from_directory(DATA_PATH + '/lib', fn)
    
'''
The following works like a proxy server:

A flask server URL of the form 
  "http://127.0.0.1:5000/5984/vl_db/000_SERVERS" 
will be forwarded to the real CouchDB URL 
  "http://127.0.0.1:5984/vl_db/000_SERVERS"

see:
https://stackoverflow.com/questions/6656363/proxying-to-another-web-service-with-flask 
'''
@app.route('/{}/'.format(COUCHDB_PORT), \
  methods=['GET','PUT','POST','HEAD','DELETE','OPTIONS']) 
@app.route('/{}/<path:p>'.format(COUCHDB_PORT),
  methods=['GET','PUSH','POST','DELETE'])
def couchdb_proxy(p=''):
    q = request.query_string.decode();
    if q:
        path = p + '?' + q
    else:
        path = p
    host = urlparse(request.base_url).hostname
    new_url = '{}://{}:{}/{}'.format(COUCHDB_PROTO, host, COUCHDB_PORT, path) 
    app.logger.debug('[old couchdb url] ' + request.url)
    app.logger.debug('[new couchdb url] ' + new_url)
    resp = requests.request(
        method=request.method,
        url=new_url,
        headers={key: value for (key, value) in request.headers if key != 'Host'},
        data=request.get_data(),
        cookies=request.cookies,
        allow_redirects=False)      
    excluded_headers = ['content-encoding', 'content-length', \
      'transfer-encoding', 'connection']
    headers = [(name, value) for (name, value) in resp.raw.headers.items()
               if name.lower() not in excluded_headers]
    response = Response(resp.content, resp.status_code, headers)
    return response  
       
if __name__ == '__main__':
    app.run(host='0.0.0.0')