from flask import Flask, request, redirect, render_template, url_for
from parsers.CSV_to_RDF_generico import parse, parsefromfile
from parsers.get_form_fields import getFormFields


app = Flask(__name__)

@app.route('/', methods=['POST','GET'])
def main():

    appath = app.root_path + '/'
    configurationFolder = 'parsers/configuration_files/'
    configurationFileName = 'configuration.json'   
    confFilePath = appath + configurationFolder + configurationFileName

    try:
        formFields = getFormFields(confFilePath)
    except:
        return redirect(url_for('error'))


    if request.method == 'POST':

        outputFolder = appath + 'samples/RDF/'

        fileFromRequest = request.files['FILE']
        filename = fileFromRequest.filename

        if filename != '':
            outFileName = fileFromRequest.filename.replace('.csv', '') + '.ttl'
            outFilePath = appath + outputFolder + outFileName
            inFile = fileFromRequest.read()
            # try to create list of dictionaries keyed by header row
            try:
                parsefromfile(confFilePath, formFields, inFile, outFilePath)
            except:
                return redirect(url_for('error'))

        else:
            # Da completare
            data =  {}
            for field in formFields:
                data[field] = request.form[field]

            check = [val for val in data.values() if val!='']

            if len(check)>0:
                outFilePath = appath + outputFolder + 'form_output.ttl'
                parse(confFilePath, formFields,[data], outFilePath)
            else:
                return redirect(url_for('error'))

        return redirect(url_for('main'))

    return render_template('index.html', data=formFields)


@app.route('/error/', methods=['POST','GET'])
def error():
    if request.method == 'POST':
        return redirect(url_for('main'))
    else:
        return render_template('error.html')


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