import tkinter as tk
from tkinter import messagebox
from selenium import webdriver
from PIL import Image, ImageTk
import csv
import time
import datetime
import threading
import smtplib
from email.message import EmailMessage

EMAIL = ''
PASSWORD = ''
EMAIL_SEND = ''
WEBSITE = ''
CLIENT_NAME = ''
SUBMISSION_STATUS = ''

def send_email():
    msg = EmailMessage()
    msg['from'] = EMAIL
    msg['to'] = EMAIL_SEND
    msg['Subject'] = 'Website was submitted successfully'
    ct = str(datetime.datetime.now())
    msg.set_content(f'Hi Al, \n\nThis is an automated email generated by Search Engine Submitter to let you know that your client ({CLIENT_NAME})\'s website ({WEBSITE}) was submitted successfully at time: {ct}. \n\nHave a good day.')
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(EMAIL, PASSWORD)
        smtp.send_message(msg)

def start_submission():
    global SUBMISSION_STATUS
    global WEBSITE
    PATH = "assets\chromedriver.exe"
    GOOGLE = 'https://search.google.com/search-console/welcome'
    BING = 'https://www.bing.com/webmasters'
    # WEBSITE = WEBSITE
    # EMAIL = EMAIL
    # PASS = PASSWORD
    print('here: ', WEBSITE, EMAIL, PASSWORD)
    driver = webdriver.Chrome(PATH)
    driver.implicitly_wait(10)


    try:
        driver.get(GOOGLE)
        email_input = '//*[@id="identifierId"]'
        next_button = '//*[@id="identifierNext"]/div/button'
        pass_input = '//*[@id="password"]/div[1]/div/div[1]/input'
        login_button = '//*[@id="passwordNext"]/div/button'

        driver.find_element_by_xpath(email_input).send_keys(EMAIL)
        driver.find_element_by_xpath(next_button).click()
        time.sleep(2.5)
        driver.find_element_by_xpath(pass_input).send_keys(PASSWORD)
        driver.find_element_by_xpath(login_button).click()
        time.sleep(10)

        if WEBSITE.find('/') == -1:
        # normal website
            enter_site_google = '//*[@id="yDmH0d"]/c-wiz/div/div[1]/span/div[3]/div[1]/div[1]/div[4]/div/div[1]/div/div[1]/input'
            submit_website_google = '//*[@id="yDmH0d"]/c-wiz/div/div[1]/span/div[3]/div[1]/div[1]/div[5]'
            verify_submit_google = '//*[@id="yDmH0d"]/div[6]/div/div[2]/div[3]/div[2]/div[1]'
            driver.find_element_by_xpath(enter_site_google).send_keys(WEBSITE)
            time.sleep(2.5)
            driver.find_element_by_xpath(submit_website_google).click()
            time.sleep(2.5)
            driver.find_element_by_xpath(verify_submit_google).click()
            time.sleep(2.5)
        else:
        # subdomain website
            if WEBSITE[0:8] != 'https://':
                WEBSITE = 'https://' + WEBSITE
                print(WEBSITE)
            enter_site_google = '//*[@id="yDmH0d"]/c-wiz/div/div[1]/span/div[3]/div[1]/div[3]/div[4]/div/div[1]/div/div[1]/input'
            submit_website_google = '//*[@id="yDmH0d"]/c-wiz/div/div[1]/span/div[3]/div[1]/div[3]/div[5]'
            verify_submit_google = '//*[@id="yDmH0d"]/div[6]/div/div[2]/div[3]/div[2]'
            driver.find_element_by_xpath(enter_site_google).send_keys(WEBSITE)
            time.sleep(2.5)
            driver.find_element_by_xpath(submit_website_google).click()
            time.sleep(2.5)
            driver.find_element_by_xpath(verify_submit_google).click()
            time.sleep(2.5)


        driver.execute_script("window.open('"+ BING +"','_blank')")
        driver.switch_to.window(driver.window_handles[1])

        #bing submission
        b_signin_btn = '//*[@id="root"]/div/header/div/div[2]/div/button[3]'
        google_card = '/html/body/div[2]/div/div/div/div[2]/div[2]/div[2]/div/div[2]'
        enter_website_bing = '//*[@id="TextField30"]'
        submit_website_bing = '//*[@id="root"]/div/div/div/div/div[3]/button'
        verify_submit_bing_1 = '/html/body/div[3]/div/div/div/div[2]/div[3]/div[3]/div/div/button[1]'
        verify_submit_bing_2 = '/html/body/div[3]/div/div/div/div[2]/div[2]/div[2]/button[1]'
                            #  '/html/body/div[3]/div/div/div/div[2]/div[3]/div[3]/div/div/button[1]'
                            #  '/html/body/div[3]/div/div/div/div[2]/div[3]/div[3]/div/div/button[1]'
        cancel_varify_bing_1 = '/html/body/div[2]/div/div/div/div[2]/div[2]/div[2]/button[1]'
        cancel_varify_bing_2 = '/html/body/div[3]/div/div/div/div[2]/div[2]/div[2]/button[1]'
        # close = '/html/body/div[3]/div/div/div/div[2]/div[3]/div[1]/button'
        #         '/html/body/div[2]/div/div/div/div[2]/div[3]/div[1]/button'
                            #  '/html/body/div[3]/div/div/div/div[2]/div[2]/div[2]/button[1]'
        driver.find_element_by_xpath(b_signin_btn).click()
        time.sleep(2.5)
        driver.find_element_by_xpath(google_card).click()
        time.sleep(2.5)
        driver.implicitly_wait(2.5)
        try:
            driver.find_element_by_xpath(cancel_varify_bing_1).click()
        except:
            try:
                driver.find_element_by_xpath(cancel_varify_bing_2).click()
            except:
                pass
        driver.implicitly_wait(10)
        time.sleep(2.5)
        driver.find_element_by_xpath(enter_website_bing).send_keys(WEBSITE)
        time.sleep(2.5)
        driver.find_element_by_xpath(submit_website_bing).click()
        time.sleep(2.5)
        driver.get(BING)
        SUBMISSION_STATUS = 'DONE'
    except:
        SUBMISSION_STATUS = 'FAIL'
    # driver.quit()

def monitor_status():
    global SUBMISSION_STATUS
    while True:
        time.sleep(0.5)
        # print('here')
        if SUBMISSION_STATUS == 'DONE':
            send_email()
            messagebox.showinfo("DONE", 'Submission has been made and an email report has been sent to you.')
            break
        if SUBMISSION_STATUS == 'FAIL':
            messagebox.showinfo("ERROR", 'An unexpexted error occured. Please double check the website\'s URL and try again.')
            break

    window.destroy()
    

        

#---------DEFINE WINDOW-----------
window = tk.Tk()
#---------DEFINE WINDOW-----------

email_address = tk.Entry()
pass_ = tk.Entry()
email_address_send = tk.Entry()
settings_window = ''

#--------LOAD ASSETS----------
load = Image.open("assets/intro.png")
intro_img = ImageTk.PhotoImage(load)
load = Image.open("assets/tagline.png")
tagline_img = ImageTk.PhotoImage(load)
load = Image.open("assets/tip.png")
tip_img = ImageTk.PhotoImage(load)
load = Image.open("assets/wait.png")
wait_img = ImageTk.PhotoImage(load)
load = Image.open("assets/wait-2.png")
wait_2_img = ImageTk.PhotoImage(load)
load = Image.open("assets/settings-header.png")
settings_header_img = ImageTk.PhotoImage(load)
#---------LOAD ASSETS------------


#---------------SCREEN 2 SETTINGS---------------------------
def move_to_screen_2():
    global WEBSITE
    global CLIENT_NAME
    # global email
    # global password
    WEBSITE = website_url.get()
    CLIENT_NAME = client_name.get()
    if WEBSITE == '' or CLIENT_NAME == '':
        messagebox.showinfo("Error", "Please enter website URL and your client's name to proceed.")
        return
    screen_1.destroy()
    settings.destroy()
    screen_2 = tk.Frame(padx=100, pady=30)
    tk.Label(screen_2, image=wait_img, pady=10).pack()
    tk.Label(screen_2, image=wait_2_img, pady=10).pack()
    tk.Label(screen_2, pady=20).pack()
    screen_2.pack()
    time.sleep(3)
    submission_thread = threading.Thread(target=start_submission, daemon=True)
    submission_thread.start()
    monitor_status_thread = threading.Thread(target=monitor_status, daemon=True)
    monitor_status_thread.start()
    # start_submission()

#---------------SCREEN 2 SETTINGS---------------------------


#---------------SETTINGS WINDOW---------------------------
def show_settings():
    global email_address
    global pass_
    global email_address_send
    global EMAIL
    global PASSWORD
    global EMAIL_SEND
    global settings_window
    settings_window = tk.Toplevel()
    settings_window.title("Configure Settings")
    frame = tk.Frame(settings_window, padx=100, pady=50)
    tk.Label(frame, image=settings_header_img, pady=10).pack()
    tk.Label(frame, text="These credentials \n will be used to sign in the webmasters for submission purposes. ", font="Segoe", pady=5).pack()
    tk.Label(frame, text="Email", font="Segoe", pady=5).pack()
    email_address = tk.Entry(frame, width=30, bd=3, justify=tk.CENTER, font="Segoe")
    email_address.insert(0, EMAIL.strip())
    email_address.pack()
    tk.Label(frame, text="Password", font="Segoe", pady=5).pack()
    pass_ = tk.Entry(frame, width=30, bd=3, justify=tk.CENTER, font="Segoe")
    pass_.insert(0, PASSWORD.strip())
    pass_.pack()
    tk.Label(frame, pady=10).pack()
    tk.Label(frame, text="The below given \n email address will be used to send email after successful subissions.", font="Segoe", pady=5).pack()
    email_address_send = tk.Entry(frame, width=30, bd=3, justify=tk.CENTER, font="Segoe")
    email_address_send.insert(0, EMAIL_SEND.strip())
    email_address_send.pack()
    tk.Label(frame, pady=15).pack()
    EMAIL = email_address.get()
    PASSWORD = pass_.get()
    EMAIL_SEND = email_address_send.get()
    tk.Button(frame, text="Save Credentials", font="Segoe", bg='#1172BC', fg='white', command=confirm_change).pack()
    frame.pack()
#---------------SETTINGS WINDOW---------------------------

def confirm_change():
    global EMAIL
    global PASSWORD
    global EMAIL_SEND
    global email_address
    global pass_
    global email_address_send
    EMAIL = email_address.get()
    PASSWORD = pass_.get()
    EMAIL_SEND = email_address_send.get()
    res = messagebox.askokcancel(title='Confirmation', message='Are you sure you want to save these credentials?')
    print(res)
    if (res):
        with open('assets/credentials.csv', 'w') as credentials:
            writer = csv.writer(credentials)
            writer.writerow([EMAIL, PASSWORD, EMAIL_SEND])
    else:
        pass
    settings_window.destroy()

#---------COBFIGURE WINDOW-----------
window.title("Search Engine Indexer")
window.iconbitmap('assets/icon.ico')
#---------COBFIGURE WINDOW-----------


#--------------SCREEN 1 SETTINGS--------------------------
screen_1 = tk.Frame(padx=100, pady=50)
tk.Label(screen_1, image=intro_img, pady=10).pack()
tk.Label(screen_1, image=tagline_img).pack()
tk.Label(screen_1, image=tip_img, pady=4).pack()
tk.Label(screen_1, pady=15).pack()
tk.Label(screen_1, text="Enter a valid website URL bellow (WITHOUT https://) e.g., (www.google.com)", font="Segoe", pady=5).pack()
website_url = tk.Entry(screen_1, width=30, bd=3, justify=tk.CENTER, font="Segoe")
website_url.pack()
tk.Label(screen_1, pady=3).pack()
tk.Label(screen_1, text="Enter your client's name. This name will be used to address your client in the email \n that you will recieve upon submission.", font="Segoe", pady=5).pack()
client_name = tk.Entry(screen_1, width=30, bd=3, justify=tk.CENTER, font="Segoe")
client_name.pack()
tk.Label(screen_1, pady=3).pack()
tk.Button(screen_1, text="Proceed", command=move_to_screen_2, width=12, height=1, bg='#1172BC', fg='white', font="Segoe").pack()
settings = tk.Button(window, text="Settings", width=15, font="Segoe", command=show_settings)



#---------------ATTACH WIDGETS------------------------------
settings.pack() 
screen_1.pack()
with open('assets/credentials.csv', 'r') as credentials:
    values = csv.reader(credentials)
    for value in values:
        EMAIL = value[0]
        PASSWORD = value[1]
        EMAIL_SEND = value[2]
        break
# cancel = tk.Button(window, text="Cancel", command=window.destroy, width=10, bg='red', fg='white', font="Segoe").pack()
tk.Label(window, pady=20).pack()
#---------------ATTACH WIDGETS------------------------------


#----------MAIN LOOP---------------
window.mainloop()
#----------MAIN LOOP---------------
