#!/usr/bin/python3

# -------------------------------------------------------------------------------------------
#  cpadmin_reset.py
#   User specifies the email to reset, locates User table entry by email
# -------------------------------------------------------------------------------------------

import os
import sys
sys.stdout.reconfigure(encoding='utf-8')
import json
import secrets, smtplib
import time
from email.mime.text import MIMEText
from dash_utils import get_connection, get_parameters, get_smtp_settings
import password_utils

# -------------------------------------------------------------------------------------------
from jinja2 import Environment, FileSystemLoader, Template
env = Environment(loader=FileSystemLoader('templates'), trim_blocks=True)

# -------------------------------------------------------------------------------------------
def render_form( tmpdict ):
    template = env.get_template('./cpadmin_reset_request.html')
    print("Content-Type: text/html; charset=utf-8\n")
    output = template.render( tmpdict )
    print(output)

# -------------------------------------------------------------------------------------------
def send_verification_email(recipient_email, verification_link):
    my_smtp = get_smtp_settings()
    SMTP_SERVER   = my_smtp.get('SMTP_SERVER','')
    SMTP_PORT     = my_smtp.get('SMTP_PORT','')
    SMTP_USER     = my_smtp.get('SMTP_USER','')
    SMTP_PASSWORD = my_smtp.get('SMTP_PASSWORD','')

    # -------------------------------------------------------------------------------------------
    subject = "CP Admin - Reset Password"
    body = f"Click the following link to Reset your Password:\n{verification_link}"
    msg = MIMEText(body)
    msg["Subject"] = subject
    msg["From"] = SMTP_USER
    msg["To"] = recipient_email

    MAX_RETRIES = 3
    for attempt in range(1, MAX_RETRIES + 1):
        try:
            with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
                server.set_debuglevel(1)
                server.ehlo()
                server.starttls()
                server.ehlo()
                server.login(SMTP_USER, SMTP_PASSWORD)
                server.sendmail(SMTP_USER, [recipient_email], msg.as_string())
            return(True)  # print("E-Mail sent successfully")
            break
        except smtplib.SMTPResponseException as e:
            #  print(f"Attempt {attempt} failed: {e.smtp_code} {e.smtp_error}")
            if attempt == MAX_RETRIES or e.smtp_code != 454:
                return(False)
                raise
            #  print("Waiting before retrying...")
            time.sleep(10)  # wait 10 seconds before retrying
    return

# -------------------------------------------------------------------------------------------

def main():

    # extract form values
    args_dict = get_parameters()
    email = args_dict.get('email', '').strip()

    if not email:
        args_dict['message'] = "Enter your E-Mail address"
        args_dict['severity'] = 'danger'
        render_form( args_dict )
        return

    db = get_connection()
    cur = db.cursor()

    # verify that the email exists and is active
    cur.execute("SELECT id FROM users WHERE email=%s AND is_active=1", (email,))
    user = cur.fetchone()
    if user:
        token = secrets.token_hex(16)
        cur.execute("UPDATE users SET verification_token=%s WHERE id=%s", (token, user["id"]))
        db.commit()

        # Done with the UPDATE, send email with token
        recipient_email = email
        verification_link = f"https://admin.crosspurposeband.com/cgi-bin/cpadmin_reset_password.py?token={ token }"
        email_sent = send_verification_email(recipient_email, verification_link)

        args_dict['message'] = f"If the E-Mail exists, you will receive a Reset link."
        args_dict['severity'] = 'warning'
        render_form( args_dict )
        db.close()

# --- entry point ---
if __name__ == "__main__":
    main()
