from wtforms import StringField, SubmitField
from multiprocessing import Process
from flask import Flask, render_template, redirect, url_for
from flask_bootstrap import Bootstrap5
from flask_wtf import FlaskForm, CSRFProtect
from vals import *
from form import FronForm
from proc import process_form
from wtforms.validators import InputRequired, Length
import secrets
# Bootstrap-Flask requires this line
app = Flask(__name__)
foo = secrets.token_urlsafe(16)
app.secret_key = foo
csrf = CSRFProtect(app)
bootstrap = Bootstrap5(app)

#GLOBALS
CONTRIBDIR = LOCALBASE + 'contributors/'
#This will change when everything is debugged
#PERSONALDIR = CONTRIBDIR + lastName + firstName[0]
PERSONDIR = CONTRIBDIR
INPUTFILE = ''
TEMPLATE = CONTRIBDIR + 'template.ft3'
diValues = {}

from form import FronForm
from proc import Fronimo

# all Flask routes below
@app.route('/', methods=['GET','POST'])
def index():
    global diValues
    form = FronForm()
    message = ""
    fron.get_defaults(diValues)
    if form.btn_cancel.data:
        return redirect('https://lutemusic.org', code=302)
    if form.validate_on_submit():
        diData = {'name':form.myname.data, 'infile': form.stInfile.data,
        'title': form.title.data, 'subtitle':form.subtitle.data, \
        'composer': form.composer.data, 'orig': form.composer0.data, \
        'ensemble': form.ensemble.data, 'part': form.part.data, \
        'key': form.key.data, 'difficulty': form.difficulty.data, \
        'type': form.type.data, 'source': form.source.data,\
        'document': form.document.data, 'volume': form.volume.data, \
        'page': form.page.data, 'date': form.date.data, \
        'section': form.section.data, 'editor': form.editor.data, \
        'encoder': form.encoder.data, 'intabulator': form.intabulator.data, \
        'arranger': form.arranger.data, 'contributor': form.contributor.data, \
        'remarks': form.remarks.data, 'outfile': form.outputfile.data}
        if diData['infile'].find(PERSONDIR) != 0:
            diData['infile'] = PERSONDIR + diData['infile']
        if not diData['outfile'].endswith('.ft3'):
            diData['outfile'] = diData['outfile'] + '.ft3'
        if process_form(diData):
            return redirect('/success', code=302)
        else:
            return redirect('/failure', code=302)
    return render_template('index.html',  form=form, message=message)

@app.route('/', methods=['GET','POST'])
class InputForm(FlaskForm):
    inputfile = StringField('Name of file to edit: ', \
    default = '', validators=[Length(0,40), input_val])
    submit = SubmitField('Submit')
    btn_cancel=SubmitField(label='Cancel',render_kw={'formnovalidate': True})

def find_values(stFile):
    fron2 = Fronimo(stFile)
    diForm["infile"] = stFile
    diForm["title"] = fron2.title
    diForm["subtitle"] = fron2.subtitle
    diForm['composer'] = fron2.composer
    diForm['composer0'] = fron2.composer0
    diForm['ensemble'] = fron2.ensemble
    diForm['part'] = fron2.part
    diForm['key'] = fron2.key
    diForm['difficulty'] = fron2.difficulty
    diForm['type'] = fron2.type
    diForm['source'] = fron2.source
    diForm['document'] = fron2.document
    diForm['volume'] = fron2.volume
    diForm['date'] = fron2.date
    diForm['page'] = fron2.page
    diForm['section'] = fron2.section
    diForm['editor'] = fron2.editor
    diForm['encoder'] = fron2.encoder
    diForm['intabulator'] = fron2.intabulator
    diForm['arranger'] = fron2.arranger
    diForm['contributor'] = fron2.contributor
    diForm['remarks'] = fron2.remarks
    diForm['outputfile'] = fron2.output
    return diForm

@app.route('/', methods=['GET', 'POST'])
def get_input():
    message = ''
    input_form = InputForm()
    if input_form.btn_cancel.data:
        return redirect('https://lutemusic.org', code=302)
    if input_form.validate_on_submit():
        stInput = input_form.inputfile.data
        if stInput == '':
            stInput = TEMPLATE
        else:
            if stInput.find(PERSONDIR) != 0:
                stInput = PERSONDIR + stInput
            if not stInput.endswith('.ft3'):
                stInput = stInput + '.ft3'
        diValues = find_values(stInput)
        print(diValues)
        return redirect('/form', code = 302)
    return render_template('input.html',  form=input_form, message=message)

@app.route('/success', methods=['GET'])
def done():
    return render_template('success.html')

@app.route('/failure', methods=['GET'])
def fail():
    return render_template('failure.html')

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