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 wtforms import (StringField, SubmitField, TextAreaField, IntegerField, RadioField)
#from wtforms.validators import InputRequired, Length, NumberRange, Optional, Regexp, ValidationError, InputRequired, DataRequired
from vals import *
from form import * 
from proc import *
import secrets
import platform
# Bootstrap-Flask requires this line
app = Flask(__name__)
foo = secrets.token_urlsafe(16)
app.secret_key = foo
csrf = CSRFProtect(app)
bootstrap = Bootstrap5(app)

#GLOBALS
currOS = platform.platform()
if currOS.find('Windows') == 0:
    LOCALBASE = 'D:/website/'
else:
    LOCALBASE = '/mnt/d/website/'

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

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

@app.route('/', methods=['GET', 'POST'])
def index():
    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'
        Fronimo.open_error(EERRFILE)
        # Open name- and type-related files
        Fronimo.open_files()
        diValues = find_values(stInput)
        do_form(diValues)
    return render_template('index.html',  form=input_form, message=message)

@app.route('/form', methods=['GET', 'POST'])
def do_form(diValues):
    form = insert_defaults(diValues)
    message = ""
    if form.btn_cancel.data:
        return redirect('https://lutemusic.org', code=302)
    if form.validate_on_submit():
        print('in if validate_on_submit')
        input()
        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'
        print('b4 process_form')
        input()
        if process_form(diData):
            return redirect('/success', code=302)
        else:
            return redirect('/failure', code=302)
    return render_template('form.html',  form=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)
