import sys
sys.path.append('/home/morgan/devel/FreeCAD-build/lib')

from flask import Flask, render_template, request, send_file
from hashlib import blake2b
import FreeCAD
import Part
import Import
import json
import time
from FreeCAD import Mesh
print(FreeCAD, Import, Part)

app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True

@app.route('/gltf/<name>.gltf')
def gen_gltf(name):
    file = './models/{}.FCStd'.format(name)

    doc = FreeCAD.openDocument(file)
    body = doc.getObject('Body')

    sheet = doc.getObject('Spreadsheet')

    sheet.set('chole', request.args['count'])
    doc.recompute()

    out_file = u'static/{}x{}.gltf'.format(name, request.args['count'])
    print('writing to {}'.format(out_file))

    Import.export([ body ], out_file)

    return send_file(out_file)

@app.route('/stl/<name>.stl')
def gen_stl(name):
    file = './models/{}.FCStd'.format(name)

    print('loading ', file)

    doc = FreeCAD.openDocument(file)
    print(doc)
    #body = doc.getObject('Body')
    # TODO support more types

    bodies = [body for body in doc.findObjects('PartDesign::Body') if body.Visibility]

    sheet = doc.getObject('Spreadsheet')

    for k in request.args:
        v = request.args[k]
        print(k, v)
        try:
            sheet.set(k, v)
        except Exception as e:
            print(e)

    doc.recompute()
    arg_hash = blake2b(bytes(json.dumps(request.args), 'utf-8'), digest_size=10).hexdigest()
    out_file = './stls/{}_{}.stl'.format(name, arg_hash)
    Mesh.export(bodies, out_file)

    return send_file(out_file)

@app.route('/upload', methods=['POST'])
def upload():
    f = request.files['upload']
    out_file = 'models/{}'.format(f.filename)
    f.save(out_file)
    
    doc = FreeCAD.openDocument(out_file)
    sheet = doc.getObject('Spreadsheet')
    cells = []
    for cell in [cell for cell in sheet.getUsedCells() if sheet.getAlias(cell)]:
        value = sheet.get(cell)

        if hasattr(value, 'Value'): value = value.Value

        cells.append({
            'cell': cell,
            'alias': sheet.getAlias(cell),
            'value': value
        })

    return json.dumps(cells)

@app.route("/")
def hello_world():
    return render_template('index.html')
