# /var/www/html/repos/protonApp/src/app.py
from flask import Flask, request, render_template, send_file, jsonify
from prepare_file import convert_to_wav, convert_to_mp3
import os
#import logging
import zipfile
import io
import serial.tools.list_ports
import threading
import time

#logging.basicConfig(filename='./flask_debug.log', level=logging.DEBUG)
#logging.debug("Flask app is loading")

app = Flask(__name__)

UPLOAD_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads')

@app.route('/')
def index():
    #logging.debug("Rendering index.html")
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'audioFile' not in request.files:
        return "No file part", 400
    files = request.files.getlist('audioFile')
    if not files or all(f.filename == '' for f in files):
        return "No selected file", 400

    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER)

    converted_files = []
    for file in files:
        if file and file.filename:
            input_path = os.path.join(UPLOAD_FOLDER, file.filename)
            output_filename = os.path.splitext(file.filename)[0] + '.wav'
            output_path = os.path.join(UPLOAD_FOLDER, output_filename)
            file.save(input_path)
            convert_to_wav(input_path, output_path)
            converted_files.append(output_filename)

    return render_template(
        'index.html',
        converted_file=converted_files if converted_files else None,
        zip_download=True if converted_files else False
    )

@app.route('/upload_mp3', methods=['POST'])
def upload_file_mp3():
    if 'audioFile' not in request.files:
        return "No file part", 400
    files = request.files.getlist('audioFile')
    if not files or all(f.filename == '' for f in files):
        return "No selected file", 400

    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER)

    converted_files = []
    for file in files:
        if file and file.filename:
            input_path = os.path.join(UPLOAD_FOLDER, file.filename)
            output_filename = os.path.splitext(file.filename)[0] + '.mp3'
            output_path = os.path.join(UPLOAD_FOLDER, output_filename)
            file.save(input_path)
            convert_to_mp3(input_path, output_path)
            converted_files.append(output_filename)

    return render_template(
        'index.html',
        converted_file=converted_files if converted_files else None,
        zip_download=True if converted_files else False
    )

@app.route('/download/<filename>')
def download_file(filename):
    file_path = os.path.join(UPLOAD_FOLDER, filename)
    if os.path.exists(file_path):
        return send_file(file_path, as_attachment=True)
    return "File not found", 404

@app.route('/download_zip')
def download_zip():
    filenames = request.args.getlist('files')
    if not filenames:
        return "No files specified", 400

    memory_file = io.BytesIO()
    with zipfile.ZipFile(memory_file, 'w') as zf:
        for filename in filenames:
            file_path = os.path.join(UPLOAD_FOLDER, filename)
            if os.path.exists(file_path):
                zf.write(file_path, arcname=filename)
    memory_file.seek(0)
    return send_file(
        memory_file,
        mimetype='application/zip',
        as_attachment=True,
        download_name='converted_files.zip'
    )

if __name__ == '__main__':
    app.run(debug=False)