import os
import smtplib
import subprocess
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import openpyxl
import random
import time
import win32com.client as win32

# Function to send email
def send_email(sender_email, recipient_email, comments):
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.Subject = 'Peer Review Results'
    mail.Body = comments
    mail.To = recipient_email

    # Attach the file
    full_file_path = os.path.join(path.get(), file.get())
    attachment = os.path.abspath(full_file_path)
    mail.Attachments.Add(attachment)

    # Display the email
    mail.Display(True)


# Function to open the selected file
def open_file():
    try:
        os.startfile(os.path.join(path.get(), file.get()))
    except FileNotFoundError:
        messagebox.showerror('Error', 'The system cannot find the file specified: ' + file.get())

# Function to submit the form
def submit():
    # Check if any question is answered with 'No'
    if 'No' in [var.get() for var in vars]:
        # Send the email
        send_email(sender_email.get(),recipient_email.get(), notes.get('1.0', tk.END))
# Function to refresh the file list

def refresh():
    files = [f for f in os.listdir(path.get()) if f.endswith('.xlsx')]
    file_dropdown['values'] = files

# Function to update the Excel file with comments
def update_excel():
    wb = openpyxl.load_workbook(file.get())
    ws = wb[sheet_name.get()]
    ws['D4'] = notes.get('1.0', tk.END)
    wb.save(file.get())

# Function to shuffle names for peer review
def shuffle_names():
    wb = openpyxl.load_workbook(file.get())
    ws = wb[sheet_name.get()]
    names = [cell.value for cell in ws['E'] if cell.value]
    random.shuffle(names)
    for i, cell in enumerate(ws['F'], start=1):
        cell.value = names[i % len(names)]
    wb.save(file.get())

# Function to generate a report
def generate_report():
    start_time = time.time()
    # Code to review the Excel file goes here
    end_time = time.time()
    report = f'Time taken for peer review: {end_time - start_time} seconds'
    return report

# Create the main window
root = tk.Tk()
root.title('Peer Review')
root.geometry('800x600')  # Set the initial window size

# Configure the style
style = ttk.Style()
style.theme_use('clam')  # Set the desired theme
style.configure('TLabel', font=('Arial', 12), background='#E0E0E0')
style.configure('TEntry', font=('Arial', 12))
style.configure('TButton', font=('Arial', 12), padding=10, relief='raised')
style.configure('TRadiobutton', font=('Arial', 12), background='#E0E0E0')

# Create a main frame
main_frame = tk.Frame(root, bg='#F0F0F0')
main_frame.pack(fill='both', expand=True, padx=20, pady=20)

# Create a left frame for the questions and a right frame for the notes
left_frame = tk.Frame(main_frame, bg='#E0E0E0')
right_frame = tk.Frame(main_frame, bg='#E0E0E0')
left_frame.pack(side='left', fill='both', expand=True, padx=10, pady=10)
right_frame.pack(side='right', fill='both', expand=True, padx=10, pady=10)

# Create entries for sender email, password, and recipient email
sender_email = tk.StringVar()
password = tk.StringVar()
recipient_email = tk.StringVar()
ttk.Label(left_frame, text='Your Email:').pack(pady=5)
sender_email_entry = ttk.Entry(left_frame, textvariable=sender_email)
sender_email_entry.pack()
ttk.Label(left_frame, text='Recipient Email:').pack(pady=5)
recipient_email_entry = ttk.Entry(left_frame, textvariable=recipient_email)
recipient_email_entry.pack()

# Create an entry to enter the path to the files
path = tk.StringVar()
ttk.Label(left_frame, text='Path:').pack(pady=5)
path_entry = ttk.Entry(left_frame, textvariable=path)
path_entry.pack()
refresh_button = ttk.Button(left_frame, text='Refresh', command=refresh)
refresh_button.pack(pady=5)

# Create a dropdown to select the file
file = tk.StringVar()
file_dropdown = ttk.Combobox(left_frame, textvariable=file)
file_dropdown.pack(pady=5)

# Create a dropdown to select the sheet name
sheet_name = tk.StringVar()
sheet_name_dropdown = ttk.Combobox(left_frame, textvariable=sheet_name)
sheet_name_dropdown.pack(pady=5)

# Create a button to open the selected file
open_file_button = ttk.Button(left_frame, text='Open File', command=open_file)
open_file_button.pack(pady=5)

# Create radio buttons for each question
questions = ['Are the correct brands considered?', 'Are the correct loan types considered?', 'Are all positive scenarios considered?', 'Are all regression scenarios considered?', 'Has spell check been completed?', 'Are all of the test steps accurate to the PBI?', 'Script(s) tested in QA for accuracy?', 'Has the test loan population been identified (loan list or SQL query)?']
vars = []
for question in questions:
    question_frame = tk.Frame(left_frame, bg='#E0E0E0')
    question_frame.pack(pady=5, fill='x')
    var = tk.StringVar(value='Yes')
    vars.append(var)
    question_label = ttk.Label(question_frame, text=question)
    question_label.pack(side='left', padx=5)
    yes_radio = ttk.Radiobutton(question_frame, text='Yes', variable=var, value='Yes')
    yes_radio.pack(side='left', padx=5)
    no_radio = ttk.Radiobutton(question_frame, text='No', variable=var, value='No')
    no_radio.pack(side='left', padx=5)

    # Create a label for the text box
    notes_label = ttk.Label(right_frame, text='Comments Box', font=('Arial', 12), background='#E0E0E0')
    notes_label.pack(pady=10)

    # Create a text box for notes in the right frame
    notes = tk.Text(right_frame, width=30, height=10, font=('Arial', 12))
    notes.pack(pady=10)

# Create a submit button
submit_button = ttk.Button(left_frame, text='Submit', command=submit)
submit_button.pack(pady=10)

# Start the main loop
root.mainloop() debug the code and make it better please slowly and also add the missing functions which need to be added , most of it is present this was the original request Alright the comments box should be clearly labeled as comments box , and change the mail part to generate a mail instead of giving "your email and your password" remove this instead it should create a new outlook mail with body ready , 2nd i want the comments section that i add in the tool to be updated to the excel file , basically any excel file i open after reviewing and closing it, the comments will be entered in the Comments Box , now the tricky part every excel file has multiple sheets and they are labeled with numbers if the tool can display the Sheet names for the comment to be added to and we can keep a common cell for adding comments that cell is D4 , 2nd i will add a name list i want it to autopopulate in a drop down for selecting the person that i will be mailing to thiswill populate in the outlook to section( will give the name list after this query ), after that i want the tool to be able to read data from a particular excel file which has these columns i am attaching a snip so basically the tool should be able to assign names in the tool + auto update the excel file accordingly So column E (Script ASsigned To) will always be populated , so read this column names , and then in the Next column F (Peer review assigned to) will be blank the tool should be able to shuffle names so peeople can peer review and it should be random and it should update the excel file as well , finally add a small report in the end for the time taken to peer review after a person closes the excel taht was reviewed initially , this is alot , so slowly read it and then give me the code