#!/usr/bin/env python

from flask import Flask, request, make_response
import argparse
import os
import sys


app = Flask(__name__)
sys.stdout = sys.stderr
DEFAULT_GROUP_ID = "100500"

storage = dict()


@app.route('/upload-<namespace>/<path:path>', methods=['POST'])
def mds_upload(namespace, path):
    global storage
    if (namespace, path) in storage:
        return make_response("Forbidden\n", 403)
    storage[(namespace, path)] = request.data
    resp = '<post key="{group_id}/{path}"></post>\n'.format(
        group_id=DEFAULT_GROUP_ID, path=path)
    return make_response(resp, 200)


@app.route('/get-<namespace>/{group_id}/<path:path>'.format(
    group_id=DEFAULT_GROUP_ID), methods=['GET'])
def mds_get(namespace, path):
    global storage
    if (namespace, path) in storage:
        return make_response(storage[(namespace, path)], 200)
    else:
        return make_response('Not found\n', 404)


@app.route('/delete-<namespace>/{group_id}/<path:path>'.format(
    group_id=DEFAULT_GROUP_ID), methods=['GET'])
def mds_delete(namespace, path):
    global storage
    if (namespace, path) in storage:
        del storage[(namespace, path)]
        return make_response('Deleted\n', 200)
    else:
        return make_response('Not found\n', 404)


@app.route('/_clear', methods=['POST'])
def mds_reset():
    global storage
    storage.clear()
    return ""


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


def parse_args(argv):
    parser = argparse.ArgumentParser(
        description='Mds stub server',
        epilog='Storage format: ${storage}/{namespace}.{path}'
    )

    parser.add_argument('--port', type=int, required=True, help='server port')
    parser.add_argument('--host', type=str, default='127.0.0.1', help='server host (default 127.0.0.1)')
    parser.add_argument('--storage', type=str, help='path to storage dir')

    return parser.parse_args()


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

    args = parse_args(sys.argv)

    global storage

    if args.storage:
        for key in os.listdir(args.storage):
            namespace, path = key.split('.')
            with open(os.path.join(args.storage, key), mode='rb') as value:
                storage[(namespace, path)] = value.read()

    app.run(args.host, args.port)


if __name__ == "__main__":
    main()
