from flask import Flask, render_template, request, jsonify
import sys
import os
from api_routes import api_routes 
import webview
from waitress import serve

if getattr(sys, 'frozen', False):
    template_folder = os.path.join(sys._MEIPASS, 'templates')
    app = Flask(__name__, template_folder=template_folder, static_url_path='/static')
else:
    app = Flask(__name__, static_url_path='/static')


#app = Flask(__name__, static_url_path='/static')
app.register_blueprint(api_routes)  # 분리된 API 라우트 등록

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

@app.route('/progress')
def progess():
    return render_template('progress.html')
    
@app.route('/oneLineProgress')
def oneLineProgess():
    return render_template('oneLineProgress.html')

# 종료 함수
def shutdown_waitress_server():
    print("Shutting down the server...")
    os._exit(0)

def destroy(window):
    print('Destroying window..')
    window.destroy()
    print('Destroyed!')

@app.route('/shutdown', methods=['POST'])
def shutdown():
    destroy(test)
    shutdown_waitress_server()
    return 'Server shutting down'

port=5000

# if __name__ == "__main__":
#     app.run(port=port, debug=True)  

test = webview.create_window('Palletizing', app)
if __name__ == "__main__":
    webview.start()
    serve(app, host="0.0.0.0", port=port)


# from flask import Flask, render_template, request
# import sys
# import os
# from api_routes import api_routes
# import webview
# from waitress import serve
# import threading

# # Flask 애플리케이션 설정
# if getattr(sys, 'frozen', False):
#     template_folder = os.path.join(sys._MEIPASS, 'templates')
#     app = Flask(__name__, template_folder=template_folder, static_url_path='/static')
# else:
#     app = Flask(__name__, static_url_path='/static')

# app.register_blueprint(api_routes)

# @app.route('/')
# def index():
#     return render_template('layer.html')

# @app.route('/progress')
# def progress():
#     return render_template('progress.html')
    
# @app.route('/oneLineProgress')
# def oneLineProgress():
#     return render_template('oneLineProgress.html')

# # 종료 함수
# def shutdown_server():
#     print("Shutting down the server...")
#     os._exit(0)

# # 종료 라우트 설정
# @app.route('/shutdown', methods=['POST'])
# def shutdown():
#     print("Shutdown request received.")
#     destroy(test)  # Webview 윈도우 종료
#     shutdown_server()  # Waitress 서버와 프로그램 종료
#     return 'Server shutting down...'

# # Webview 윈도우 종료 함수
# def destroy(window):
#     print('Destroying window..')
#     window.destroy()
#     print('Destroyed!')

# # 서버 실행
# port = 5000
# test = webview.create_window('Palletizing', app)

# if __name__ == "__main__":
#     # Webview와 Waitress 서버를 별도 스레드로 실행
#     server_thread = threading.Thread(target=lambda: serve(app, host="0.0.0.0", port=port))
#     server_thread.start()
#     webview.start()
