from flask import Flask
import pygame
import time
from threading import Thread
from flask_mail import Mail, Message

app = Flask(__name__)

# Configure email settings
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'your_email@gmail.com'  # Your email address
app.config['MAIL_PASSWORD'] = 'your_app_password'    # Your email app password

mail = Mail(app)

def play_music():
    pygame.mixer.init()
    # Use a generic path for the music file
    pygame.mixer.music.load("/path/to/your/song.mp3")
    pygame.mixer.music.play()

    while pygame.mixer.music.get_busy():
        time.sleep(1)

    pygame.mixer.quit()

def send_good_morning_email():
    try:
        msg = Message(
            subject="Good Morning!",
            sender=app.config['MAIL_USERNAME'],
            recipients=["recipient_email@gmail.com"],  # Recipient email
            html="<h1>Good Morning!</h1><p>Hope you enjoy the IoT project</p>"
        )
        mail.send(msg)
        return "Email sent successfully!"
    except Exception as e:
        return f"Failed to send email: {e}"

@app.route('/esp32-connect', methods=['GET'])
def esp32_connect():
    music_thread = Thread(target=play_music)
    music_thread.start()
    
    email_result = send_good_morning_email()
    
    return email_result

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)
