from flask import Flask, render_template, request
import sys
import os
from streamer import stream_gcode_websocket
from text_to_gcode import convert_text

import svgToGcode

app = Flask(__name__)


ALLOWED_EXTENSIONS_SVG_FORM = {'svg'}
ALLOWED_EXTENSIONS_GCODE_FORM = {'gcode'}


def allowed_file_svg(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS_SVG_FORM 
           
def allowed_file_gcode(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS_GCODE_FORM
           


@app.route("/", methods=["POST", "GET"])
def index():
    return render_template("form.html")
    
    
    

@app.route("/svg_file", methods=["POST", "GET"])
def getSVG():

    if request.method == "POST":
        
        file = request.files.get("file")
        if file and allowed_file_svg(file.filename):
        
            output = 'gcode_output.gcode'
            
            gcode = svgToGcode.convertToGcode(file.read() ,output)
 
            stream_gcode_websocket(gcode.splitlines())
            print(gcode)
            print("done!")
        else:
            print('unaccepted file')
    
    
    return render_template("form.html")

@app.route("/gcode_file", methods=["POST", "GET"])
def getGcode():

    if request.method == "POST":
        
        file = request.files.get("file")
        
        if file and allowed_file_gcode(file.filename):
        
            gcode = file.readlines()
            print(str(gcode))
            stream_gcode_websocket(gcode)
            
        else:
            print('empty file or unaccepted file')
    
    return render_template("form.html")        
            
                    
@app.route("/text", methods=["POST", "GET"])
def getText():
    if request.method == "POST":
        txt = request.form["txt"].strip()  # Récupère le texte de la textarea
        print(txt)
        if txt:
            # Conserver les retours à la ligne dans le texte saisi
            formatted_text = ""
            for line in txt.splitlines():  
                words = line.split()  
                current_line = ""
                for word in words:
                    if len(current_line) + len(word) + 1 > 20:  # Limite de caractères par ligne
                        formatted_text = formatted_text + current_line.strip() + "\n"
                        current_line = word + " "
                    else:
                        current_line = current_line + word + " "
                if current_line.strip():  # Ajoute la dernière ligne
                    formatted_text = formatted_text + current_line.strip() + "\n"

            print("Formatted text with line breaks:")
            print(formatted_text)

            # Générez le G-code à partir du texte formaté
            gcode_output = convert_text(formatted_text)
            # print("G-code generated:")
            # print(gcode_output)

            # Sauvegardez le fichier G-code
            gcode_filename = "retourligne.gcode"
            with open(gcode_filename, "w") as gcode_file:
                gcode_file.write(gcode_output)
            
            print("Streaming ...")
            stream_gcode_websocket(gcode_output.split("\n")) #envoi du gcode généré au plotter

            print(f"G-code saved to {gcode_filename}")
        else:
            print('empty text')

    return render_template("form.html")






