import smtplib, ssl, database, time

def send(subject, message, recipient, type):
    hour_ago = int(time.time()) - 3600
    count = database.fetch("SELECT COUNT(*) FROM email WHERE time > ?", [hour_ago])
    if count[0][0] > 5:
        return False

    database.execute("INSERT INTO email (recipient, time, type) VALUES (?, ?, ?)", [
            recipient,
            int(time.time()),
            type
        ])

    smtp_server = "webspace29.do.de"
    port = 587  # For starttls
    sender_email = "system@bnd.wtf"
    password = ""
    message = f"""From: system@bnd.wtf\nSubject: {subject}

    {message}"""

    # Create a secure SSL context
    context = ssl.create_default_context()

    # Try to log in to server and send email
    try:
        server = smtplib.SMTP(smtp_server,port)
        server.ehlo() # Can be omitted
        server.starttls(context=context) # Secure the connection
        server.ehlo() # Can be omitted
        server.login(sender_email, password)
        server.sendmail(sender_email, recipient, message)
        # TODO: Send email here
    except Exception as e:
        # Print any error messages to stdout
        print(e)
    finally:
        server.quit()

    return True
