'''

@author: olivier.massot, sept 218
'''
from tempfile import TemporaryDirectory

from flask import request
from flask.app import Flask
from flask.templating import render_template
from path import Path
from werkzeug.utils import secure_filename

from core.constants import MAIN
from schemas.netgeo_2_2_doe.validator import Netgeo22DoeValidator


app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    return render_template("index.html", validation_error="")

@app.route('/report', methods=['POST'])
def report():
    try:
        f = request.files['dossier']
    except KeyError:
        return render_template("index.html", validation_error="Aucun fichier sélectionné")
    
    filename = secure_filename(f.filename)
    
    if Path(filename).ext != ".zip":
        return render_template("index.html", validation_error="Le fichier doit être un fichier .ZIP ({})".format(Path(filename).ext))
    
    try:
        with TemporaryDirectory(dir=MAIN / "upload") as d:
            filename = Path(d) / filename
            f.save(filename)
            report = Netgeo22DoeValidator.submit(filename)
    except Exception as e:
        return render_template("index.html", validation_error=str(e))
    
    return render_template("report.html", report=report)

