
import tkinter as tk
from tkinter import messagebox
import re
import webbrowser
import requests  # Make sure to install this library if you haven't already
import os




# Function to get the device MAC address
def get_mac_address():
    return '13:bb:81:47:b2:e6'

# Function to generate a 16-digit unique ID
def get_unique_id():
    return 'cf4650bb871111ef'

# Function to handle the "Check Device" button
def check_device():
    response = messagebox.askyesno("Check Device", "Do you want to check your device?")
    if response:  # User clicked "Yes"
        email_label.pack()
        email_entry.pack()
        submit_button.pack()

# Function to validate and submit the entered email and call the send-otp API
def submit_email():
    email = email_entry.get()
    if re.match(r"[^@]+@[^@]+\.[^@]+", email):  # Simple email validation
        messagebox.showinfo("Success", f"Email submitted: {email}")
        with open('authenticated', 'w') as flag:
            flag.write('Authenticated!')

        # Replace 'your_api_url' with the actual URL of your API
        api_url = 'http://127.0.0.1:8000/send-otp/'
        try:
            response = requests.post(api_url, data={"email": email})  # Adjust the payload as needed
            if response.status_code == 200:
                messagebox.showinfo("Success", "OTP sent successfully! Please verify OTP on the web.")
                webbrowser.open('http://127.0.0.1:8000/signup') 

                # Show OTP verification window after successful OTP request
                # root.after(600000, show_otp_verification_window, email)
                show_otp_verification_window(email)
            else:
                messagebox.showwarning("Error", "Failed to send OTP.")
        except Exception as e:
            messagebox.showerror("Error", f"An error occurred: {str(e)}")
    else:
        messagebox.showwarning("Error", "Invalid email entered")

# Function to show OTP verification window
def show_otp_verification_window(email):
    otp_window = tk.Toplevel(root)
    otp_window.title("Verify OTP")
    otp_window.geometry("300x200")

    otp_label = tk.Label(otp_window, text="Enter the OTP:")
    otp_label.pack(pady=10)

    # Entry field for OTP
    otp_entry = tk.Entry(otp_window)
    otp_entry.pack(pady=10)

    # Button to verify OTP
    verify_button = tk.Button(otp_window, text="Verify OTP", command=lambda: verify_otp(otp_entry.get(), email, otp_window))
    verify_button.pack(pady=10)

    # Focus on the OTP entry field
    otp_entry.focus_set()

def verify_otp(otp, email, window):
    api_url = 'http://127.0.0.1:8000/verify-second-otp/'
    try:
        # Include the second_otp and email in the payload
        response = requests.post(api_url, data={
            "second_otp": otp, 
           
        })

        if response.status_code == 200:
            # Extract user_profile_id from the response
            response_data = response.json()
            user_profile_id = response_data.get("user_profile_id")
            print(user_profile_id)

            messagebox.showinfo("Success", "OTP verified successfully!")

            window.destroy()  # Close OTP window on successful verification
            
            # After OTP is verified, send device info with user_profile_id
            send_device_info(user_profile_id)

        else:
            messagebox.showwarning("Error", "Invalid or expired OTP.")
    except Exception as e:
        messagebox.showerror("Error", f"An error occurred: {str(e)}")
def print_device_id():
    device_id = os.environ.get('DEVICE_ID')  # Retrieve the device ID from the environment variable
    if device_id:
        print("Device ID from OS environment:", device_id)
        messagebox.showinfo("Device ID", f"Device ID: {device_id}")  # Show in a message box
    else:
        print("Device ID not found in OS environment.")
# Function to send the device information after OTP is verified
# def send_device_info(user_profile_id):
#     device_info_url = 'http://127.0.0.1:8000/send-device-info/'  # Adjust to the correct API endpoint
#     mac_address = get_mac_address()  # Get MAC address
#     unique_id = get_unique_id()  # Get unique ID

#     try:
#         # Make the POST request to send the device info
#         response = requests.post(device_info_url, json={
#             "user_profile_id": user_profile_id,  # Use the user_profile_id from OTP verification
#             "mac_address": mac_address,
#             "unique_id": unique_id
#         })

#         if response.status_code == 200:

#             messagebox.showinfo("Success", "Device info sent successfully!")
#             webbrowser.open('http://127.0.0.1:8000/home')
#             root.destroy()
#         else:
#             messagebox.showwarning("Error", f"Failed to send device info. {response.json().get('error')}")

#     except Exception as e:
#         messagebox.showerror("Error", f"An error occurred while sending device info: {str(e)}")
def send_device_info(user_profile_id):
    device_info_url = 'http://127.0.0.1:8000/update-device/'  # API endpoint
    mac_address = get_mac_address()  # Function to get MAC address
    unique_id = get_unique_id()  # Function to get unique ID

    try:
        # Make the PUT request to send the device info
        response = requests.put(device_info_url, json={
            "user_id": user_profile_id,  # Use user_profile_id from OTP verification
            "mac_address": mac_address,
            "unique_id": unique_id
        })

        if response.status_code == 200:
            messagebox.showinfo("Success", "Device info sent successfully!")
            webbrowser.open('http://127.0.0.1:8000/home')
        else:
            messagebox.showwarning("Error", f"Failed to send device info. {response.json().get('error')}")

    except Exception as e:
        messagebox.showerror("Error", f"An error occurred while sending device info: {str(e)}")



# Create the main window
root = tk.Tk()
root.title("Device Info Checker")
root.geometry("300x300")

# Create and pack the button to check the device
check_button = tk.Button(root, text="Check Device", command=check_device)
check_button.pack(pady=20)

# Label and entry for email input (hidden initially)
email_label = tk.Label(root, text="Enter your email:")
email_entry = tk.Entry(root)
submit_button = tk.Button(root, text="Submit", command=submit_email)


# Run the GUI loop
root.mainloop()
#===========================================================================this is working =============================
#