#!/usr/bin/python
from flask import Flask, make_response
from collections import defaultdict
import os
import sys

app = Flask(__name__)

PORT=int(sys.argv[1])

MDS_GROUP = 4242
RESPONSE_TEMPLATE = '<post key="{mds_group}/{path}"></post>'

MDS_STORAGE = defaultdict(list)

@app.route('/upload-mpro-dataset/<mds_dataset_path>/<dataset_id>/<file_name>', methods=['POST'], defaults={'region':''})
@app.route('/upload-mpro-dataset/<mds_dataset_path>/<dataset_id>/<region>/<file_name>', methods=['POST'])
def upload_to_mds_storage(mds_dataset_path, dataset_id, region, file_name):
    if file_name in MDS_STORAGE[(dataset_id, region)]:
        return make_response("", 403)

    MDS_STORAGE[(dataset_id, region)].append(file_name)
    return RESPONSE_TEMPLATE.format(
        mds_group=MDS_GROUP,
        path=os.path.join(mds_dataset_path, dataset_id, region, file_name))

@app.route('/delete-mpro-dataset/<group_id>/<mds_dataset_path>/<dataset_id>/<file_name>', methods=['GET'], defaults={'region':''})
@app.route('/delete-mpro-dataset/<group_id>/<mds_dataset_path>/<dataset_id><region>/<file_name>', methods=['GET'])
def delete_from_mds_storage(group_id, mds_dataset_path, dataset_id, region, file_name):
    if file_name in MDS_STORAGE[(dataset_id, region)]:
        MDS_STORAGE[(dataset_id, region)].remove(file_name)
        return make_response('')
    return make_response('', 404)

if __name__ == '__main__':
    app.run(port=PORT)
