from flask import Flask, request, redirect, render_template
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():

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

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


    if request.method == 'POST':

        outputFolder = 'samples/RDF/'

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

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

        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:
                parse(confFilePath, formFields,[data], outputFolder + 'form_output.ttl')
            else:
                return redirect('/error/')

        return redirect('/')

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


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


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