#!/usr/bin/env python3
import os
import json

from flask import Flask
from flask import Flask, request, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename

import SotMDeckBuilder

app = Flask(__name__)

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() == "json"

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename).replace(".json", "")
            SotMDeckBuilder.makeCards(json.load(file.stream),
                                      filename, "result", request.url_root + "result/")
            return redirect(url_for('get_result', filename=filename + ".json"))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

@app.route('/result/<filename>')
def get_result(filename):
    return send_from_directory("result", filename, as_attachment=True)

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0')
