# -*- coding: utf-8 -*-

from turtle import st
from flask import Flask, render_template, request, flash, redirect, url_for
from werkzeug.utils import secure_filename
import os
from models import db
from models import PrintedDetal
import logging
from models import PrintedDetal

logging.basicConfig(filename='app.log', encoding='utf-8', level=logging.DEBUG)


UPLOAD_IMG_FOLDER = os.path.join('static', 'img', 'uploads')
UPLOAD_STL_FOLDER = os.path.join('static', 'stl')
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'stl'}

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['UPLOAD_FOLDER'] = UPLOAD_IMG_FOLDER
app.config['UPLOAD_FOLDER2'] = UPLOAD_STL_FOLDER

db.init_app(app)


@app.route("/")
def index():
    #detals = PrintedDetal.query.all()

    return render_template("index.html") #  , detals=detals)


@app.route("/admin",  methods=['GET', 'POST'])
def admipage():
    logging.debug("adminpage loaded")
    if request.method == 'POST':
        logging.debug("POST QUERY loaded")


        image_file = request.files['imgfile']
        stl_file = request.files['stlfile']
        
        logging.debug(image_file)
        logging.debug(stl_file)

        image_file.save(os.path.join(app.config['UPLOAD_FOLDER'], image_file.filename))
        stl_file.save(os.path.join(app.config['UPLOAD_FOLDER2'], stl_file.filename))

        if request.form.get('isprinted') == 'on':
            isprinered = True
        else:
            isprinered = False

        logging.debug(image_file)
        logging.debug(stl_file)
        logging.debug(isprinered)

        #detal = PrintedDetal(imgpath=image_file.filename, 
        #                    stlpath=stl_file.filename, 
        #                    isprinted=isprinered)
        #db.session.add(detal)
        #db.session.commit()

        return render_template("adminpage.html")

    else:
        return render_template("adminpage.html")

@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
   if request.method == 'POST':
      f = request.files['file']
      f.save(secure_filename(f.filename))
      return 'file uploaded successfully'
if __name__ == "__main__":
    app.run(host="0.0.0.0", debug="True", port="3800")
