# The routes are the different URLs that the application implements. In Flask, handlers for the application routes are written as Python functions, called view functions. View functions are mapped to one or more route URLs so that Flask knows what logic to execute when a client requests a given URL.
from flask import render_template, redirect, flash
from app import app
import thread

import sys
sys.path.append("../E3_PostProcessor")

sys.path.append("../E3_Sender")

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    from app.forms import EngraveForm
    import E3PostProcessor, E3ImageEditor, E3Sender

    form = EngraveForm()
    if form.validate_on_submit():

        # Getting image file from form
        imageFile = form.imageFile.data

        # Creating E3ImageEditor Object
        imgEdit = E3ImageEditor.E3ImageEditor(imageFile)

        # Processing basic images trasformations
        imgEdit.ResizeKeepingAspectRatioMM(25)
        imgEdit.ConvertTo8BitBW()

        if form.mirror.data:
            imgEdit.mirror()

        if form.flip.data:
            imgEdit.flip()

        # imgEdit.img.show()

        # Creating PostProcessor object
        pp = E3PostProcessor.E3PostProcessor(imgEdit.getImage())

        # Seting up PP objet with form data
        pp.travelSpeed = int(form.travelSpeed.data)
        pp.engraveSpeed = int(form.engraveSpeed.data)
        pp.whiteValue = int(form.whiteValue.data)

        # Converting image to Gcode
        pp.processImageArray()

        # Creating Sender object
        try:
            sender = E3Sender.E3Sender("/dev/ttyS0", 9600)
        except Exception as e:
            flash(e)
            return render_template('engraveForm.html', title='Engrave', form=form)

        # Loading Gcodes to Sender
        sender.gcodeList = pp.GcodeLines

        # Running engrave process
        thread.start_new_thread(sender.runAll, ())

        return render_template("engraveDone.html", \
            title="Engraving underway")
    return render_template('engraveForm.html', title='Engrave', form=form)

@app.route("/about")
def about():
    return render_template('about.html', title="About")

@app.route("/credits")
def credits():
    return render_template('credits.html', title="Credits")
@app.route("/stream")
def stream():
    return render_template('streaming.html', title="Streaming")
