import pyautogui
def apply_job(i):
    
    try:

        mm=3
    

        time.sleep(5)
        # Wait for the "Apply" button to be clickable in the new tab
        apply_button_xpath = '//*[@id="mainContent"]/div/div[2]/div/div/section/div/div[1]/div[3]/div/div/div[2]/div/div/div/a'
        
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, apply_button_xpath)))

        # Find the "Apply" button element and click on it
        apply_button = driver.find_element(By.XPATH, apply_button_xpath)
        #print(apply_button.is_enabled())
        apply_button.click()
        time.sleep(5)


        # if 'viewApplication' in driver.current_url:
        #     return

        # Wait for the "Use My Last Application" tab to be clickable
        use_last_app_tab_xpath = '/html/body/div[2]/div/div/div/div[2]/div/div/div[1]/div[6]/div/div/a'
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, use_last_app_tab_xpath)))
        

        # Find the "Use My Last Application" tab and click on it
        use_last_app_tab = driver.find_element(By.XPATH, use_last_app_tab_xpath)
        use_last_app_tab.click()
        time.sleep(5)


        if True:
                # Wait for the "Sign In" prompt to appear
            sign_in_form_xpath = '//*[@id="wd-Authentication-NO_METADATA_ID-uid6"]/div/div[1]/div/form'
            WebDriverWait(driver, 15).until(EC.visibility_of_element_located((By.XPATH, sign_in_form_xpath)))

                # Find the email and password input fields and enter your credentials
            email_input_xpath = '//*[@id="input-4"]'
            password_input_xpath = '//*[@id="input-5"]'

            email = "rahulkotian26@gmail.com"
            password = "!-WbNZwHPncL5ZG"

            email_input = driver.find_element(By.XPATH, email_input_xpath)
            password_input = driver.find_element(By.XPATH, password_input_xpath)

            email_input.send_keys(email)
            password_input.send_keys(password)

                # Find the "Sign In" button and wait for it to become clickable before clicking
            sign_in_button_xpath = '//*[@id="wd-Authentication-NO_METADATA_ID-uid6"]/div/div[1]/div/form/div[3]/div/div/div/div/div'
            sign_in_button = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, sign_in_button_xpath)))

                # Scroll into view to ensure the element is clickable
            driver.execute_script("arguments[0].scrollIntoView();", sign_in_button)

                # Use the Actions class to simulate a click on the "Sign In" button
            actions = ActionChains(driver)
            actions.move_to_element(sign_in_button).click().perform()

        


        time.sleep(5)

        actions = ActionChains(driver)



            # Wait for the "How Did You Hear About Us?" field to be present
        how_hear_about_us_xpath = '//*[@id="input-1"]'
        WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.XPATH, how_hear_about_us_xpath)))

        time.sleep(2)

            # Find the "How Did You Hear About Us?" field and enter "Career" using ActionChains
        how_hear_about_us_input = driver.find_element(By.XPATH, how_hear_about_us_xpath)
            
        time.sleep(2)
            
            # Enter "Career"
        actions.move_to_element(how_hear_about_us_input).click().send_keys("Career Site").perform()

        time.sleep(2)

        #ENTER KEY
        actions.move_to_element(how_hear_about_us_input).click().send_keys(Keys.ENTER).perform()


        time.sleep(5)
 
        # Find the "SAVE AND CONTINUE" button by class name and click on it
        save_and_continue_button_class = 'css-d4ya5t'
        save_and_continue_button = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CLASS_NAME, save_and_continue_button_class)))

        # Scroll into view to ensure the element is clickable
        driver.execute_script("arguments[0].scrollIntoView();", save_and_continue_button)

        # Click the "SAVE AND CONTINUE" button
        save_and_continue_button.click()


 
        time.sleep(2)


        # Function to check if the confirmation message appears
        def is_upload_successful(driver):
            try:
                # Wait for the confirmation message to appear
                confirmation_message = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[contains(text(), 'Successfully Uploaded!')]")))
                return True
            except Exception as e:
                print("Exception in is_upload_successful:", e)
                return False

        # Function to check if the resume has been uploaded
        def is_resume_uploaded(driver):
            try:
                # Find the element that contains the uploaded resume by its data-automation-id
                uploaded_resume = driver.find_element(By.CSS_SELECTOR, '[data-automation-id="file-upload-item"]')
                # If the element is found, return True (resume is uploaded)
                return True
            except Exception as e:
                print("Exception in is_resume_uploaded:", e)
                # If the element is not found, return False (resume is not uploaded)
                return False


        # Define maximum number of attempts
        max_attempts = 3
        current_attempt = 0
        success = False

        # Define typing interval
        typing_interval = 0.1
        typing_interval1 = 0.0001


        # Define pause time between actions
        pause_time = 2

        while current_attempt < max_attempts and not success:
            try:
                # Check if the element with data-automation-id="formField-jobTitle" exists
                job_title_field_exists = False
                try:
                    job_title_field = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, '[data-automation-id="formField-jobTitle"]')))
                    job_title_field_exists = True
                except:
                    pass

                if not job_title_field_exists:
                    # Proceed with work experience part
                    work_exp_button = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#mainContent > div > div.css-12izqjd > div:nth-child(3) > div:nth-child(1) > div > div > div > button')))
                    work_exp_button_exists = True
                    # Work Experience
                    work_exp_button.click()
                    time.sleep(pause_time)
                    time.sleep(pause_time)
                        
                    # Type job details
                    job_details = [
                        (" Data Analyst", '\t'), 
                        ("Dynamic Sustainability Lab", '\t'),  
                        ("Syracuse, NY", '\t'), 
                        ("a", '\t'), 
                        ("072022", '\t'),  
                        ("a", '\t'), 
                        ("052023", '\t'),   
                        ("a", '\t')
                    ]

                    for detail, key in job_details:
                        pyautogui.typewrite(detail, interval=typing_interval)
                        time.sleep(pause_time)
                        pyautogui.press(key)
                        time.sleep(pause_time)
                    
                    # Type job descriptions
                    job_descriptions = [
                        "Executed in-depth analysis of over 150 energy measurement points for a $2.11 billion enterprise, leveraging Power BI, Report Designer BI, and EnergyCAP, which unveiled the potential for a 5% efficiency enhancement in energy resource utilization.",
                        "Initiated the creation of an advanced Power BI dashboard, amalgamating diverse data sources, performing Data Mining and Data Wrangling, designing custom visualizations, and consistently updating senior leadership.",
                        "Orchestrated the roll-out of an innovative energy resource tracking system using Power BI and SQL Server Analysis Services (SSAS), targeting an anticipated 15% reduction in energy usage.",
                        "Articulated data-driven models, findings, and insights to senior management, influencing informed decision-making during the transition to a Carbon NetZero economy. The data dictionary was instrumental in communicating complex data concepts."
                    ]
                    
                    for description in job_descriptions:
                        pyautogui.typewrite(description, interval=typing_interval1)
                        pyautogui.press('Enter')
                        #time.sleep(0.1)  # Adjust as needed

                    time.sleep(pause_time)

                    pyautogui.press('tab')
                    pyautogui.press('tab')

                    # Education 1
                    education_button_element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#mainContent > div > div.css-12izqjd > div:nth-child(3) > div:nth-child(3) > div > div > div > button')))
                    education_button_element.click()
                    time.sleep(2 * pause_time)  # Longer pause after clicking the education button

                    # Type education details
                    education_details = [
                        "Syracuse University School Of Information Studies", '\t', 'M', '\t', 'Information systems', '\n', '\n', '\t', '\t', '3.67', '\t', '2021', '\t', '2023', '\t'
                    ]

                    for education_detail in education_details:
                        pyautogui.write(education_detail, interval=typing_interval)  # Use write for all elements
                        time.sleep(2 * pause_time)  # Longer pause after typing each detail

                    # Education 2
                    education_button_element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#mainContent > div > div.css-12izqjd > div:nth-child(3) > div:nth-child(3) > div > div > div > button')))
                    education_button_element.click()
                    time.sleep(2 * pause_time)  # Longer pause after clicking the education button

                    # Type education details
                    education_details = [
                        "Mumbai University", '\t', 'B', '\t', 'Computer Engineering', '\n', '\n', '\t', '\t', '3.3', '\t', '2016', '\t', '2020', '\t', '\t', '\t'
                    ]

                    for education_detail in education_details:
                        pyautogui.write(education_detail, interval=typing_interval)  # Use write for all elements
                        time.sleep(2 * pause_time)  # Longer pause after typing each detail
            
                    # ... Your work experience code goes here ...
                    pass
                else:
                    # Skip to check resume
                    
                    # Resume Upload
                    if not is_resume_uploaded(driver):
                        # Wait for the "SELECT FILE" button to be clickable
                        select_file_button_css_selector = '#mainContent > div > div.css-12izqjd > div:nth-child(3) > div:nth-child(7) > div > div > div:nth-child(1) > div'
                        # Find the "SELECT FILE" button and click on it
                        select_file_button = driver.find_element(By.CSS_SELECTOR, select_file_button_css_selector)
                        select_file_button.click()
                        time.sleep(1)
                        # Specify the path to your PDF file
                        pdf_file_path = 'Rahul_Kotian_Resume.pdf'
                        # Use pyautogui to type the file path and press Enter
                        pyautogui.write(pdf_file_path)
                        pyautogui.press('Enter')
                        time.sleep(1)

                    # Check if the upload was successful
                    if is_upload_successful(driver):
                        # Set success to True to break the loop
                        success = True

            except Exception as e:
                print(f"Attempt {current_attempt + 1} failed:", e)
                current_attempt += 1
                # Wait for a brief moment before retrying
                time.sleep(2)

        # If successful, find and click the "SAVE AND CONTINUE" button
        if success:
            try:
                save_and_continue_button = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CLASS_NAME, 'css-d4ya5t')))
                driver.execute_script("arguments[0].scrollIntoView();", save_and_continue_button)
                save_and_continue_button.click()
            except Exception as e:
                print("Error while saving and continuing:", e)
        else:
            print("Max attempts reached. Skipping the action.")




        time.sleep(5)

        # Press the Tab key
        pyautogui.press('tab')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key again
        pyautogui.press('Y')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key
        pyautogui.press('tab')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key again
        pyautogui.press('o')
        time.sleep(mm)
        pyautogui.press('o')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key
        pyautogui.press('tab')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key again
        pyautogui.press('Y')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key
        pyautogui.press('tab')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key again
        pyautogui.typewrite("18", interval=0.4)

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key
        pyautogui.press('tab')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key again
        pyautogui.press('H')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key
        pyautogui.press('tab')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key again
        pyautogui.press('Y')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key
        pyautogui.press('tab')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key again
        pyautogui.press('N')

        # Press the Tab key
        pyautogui.press('tab')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key again
        pyautogui.press('N')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key
        pyautogui.press('tab')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key again
        pyautogui.press('N')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key
        pyautogui.press('tab')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key again
        pyautogui.press('N')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)

        # Press the Tab key
        pyautogui.press('tab')

        time.sleep(mm)

        # Press the Tab key again
        pyautogui.press('N')

        # Add a short delay between the Tab presses (adjust as needed)
        time.sleep(mm)


            # Find the "SAVE AND CONTINUE" button by class name and click on it
        save_and_continue_button_class = 'css-d4ya5t'
        save_and_continue_button = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CLASS_NAME, save_and_continue_button_class)))


            # Scroll into view to ensure the element is clickable
        driver.execute_script("arguments[0].scrollIntoView();", save_and_continue_button)


            # Click the "SAVE AND CONTINUE" button
        save_and_continue_button.click()

        time.sleep(5)

        pyautogui.press('tab')
        time.sleep(mm)
        pyautogui.press('tab')  
        time.sleep(mm)
        pyautogui.press('tab')
        time.sleep(mm)
        # Press the Tab key
        pyautogui.press('tab')
        time.sleep(mm)
        pyautogui.press('tab')
        time.sleep(mm)

        # Press the Tab key again
        pyautogui.press('Space')
        time.sleep(mm)


            # Find the "SAVE AND CONTINUE" button by class name and click on it
        save_and_continue_button_class = 'css-d4ya5t'
        save_and_continue_button = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CLASS_NAME, save_and_continue_button_class)))

            # Scroll into view to ensure the element is clickable
        driver.execute_script("arguments[0].scrollIntoView();", save_and_continue_button)   

            # Click the "SAVE AND CONTINUE" button
        save_and_continue_button.click()



        time.sleep(5)



        #ENTER KEY
        #actions.move_to_element(NAME_input).click().send_keys(Keys.ENTER).perform()


        time.sleep(mm)
        # Find the "SAVE AND CONT" button by class name and click on it
        save_and_continue_button_class = 'css-d4ya5t'
        save_and_continue_button = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CLASS_NAME, save_and_continue_button_class)))

            # Scroll into view to ensure the element is clickable
       # driver.execute_script("arguments[0].scrollIntoView();", save_and_continue_button)

            # Click the "SAVE AND CONTINUE" button
        save_and_continue_button.click()




        time.sleep(5)
        # Find the "SUBMIT" button by class name and click on it
        save_and_continue_button_class = 'WDKN WEWO WC3N WKLN WHKN'
        save_and_continue_button = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CLASS_NAME, save_and_continue_button_class)))

            # Scroll into view to ensure the element is clickable
        driver.execute_script("arguments[0].scrollIntoView();", save_and_continue_button)

            # Click the "SAVE AND CONTINUE" button
        save_and_continue_button.click()
    
    finally:
        # Close the browser tab
       # driver.close()
        print("Successfully applied to the job")
        return
    
    





import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import time
import pyautogui


# URL of the webpage you want to open
url = "https://walmart.wd5.myworkdayjobs.com/en-US/WalmartExternal?locationCountry=bc33aa3152ec42d4995f4791a106ed09&jobFamilyGroup=e83ebdbd2a0a01af0185848948e94dc6&jobFamilyGroup=e83ebdbd2a0a01e7e1477a8948e904c6"

# Path to the ChromeDriver executable
chromedriver_path = "Desktop/DESK/myworkdayjobs-master/chromedriver_mac64/chromedriver"  # Removed .exe for Mac compatibility

# Set up ChromeOptions and specify the executable path
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(f"executable_path={chromedriver_path}")

# Create a Chrome WebDriver instance with the specified options
driver = webdriver.Chrome(options=chrome_options)

    # Open the webpage
# driver.get(url)

time.sleep(5)


first_list_xpath = '/html/body/div[1]/div/div/div[3]/div/div/div[2]/section/div[2]/nav/div/button'
next_list_xpath = '/html/body/div[1]/div/div/div[3]/div/div/div[2]/section/div[2]/nav/div/button[2]'
m=0
j = m%20 


for i in range(m,9999):
    # Set up ChromeOptions and specify the executable path
    if j ==20 :
        j = 0
    if j != 20:
        j = j + 1

    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument(f"executable_path={chromedriver_path}")

    # Create a Chrome WebDriver instance with the specified options
    driver = webdriver.Chrome(options=chrome_options)
    driver.get(url)

    if True:
        if i >=20:
            first_list_xpath = '/html/body/div[1]/div/div/div[3]/div/div/div[2]/section/div[2]/nav/div/button'

            time.sleep(2)
            # Wait for the first job to be clickable
            WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, first_list_xpath)))

            # Find the first job element and click on it
            first_job = driver.find_element(By.XPATH, first_list_xpath)
            first_job.click()

            time.sleep(2)

        if i>=40:

            for i in range(1,int(i/20)):
                first_job_xpath = '/html/body/div[1]/div/div/div[3]/div/div/div[2]/section/div[2]/nav/div/button[2]'
                time.sleep(2)

                # Wait for the first job to be clickable
                WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, first_job_xpath)))

                    # Find the first job element and click on it
                first_job = driver.find_element(By.XPATH, first_job_xpath)
                first_job.click()
                time.sleep(2)

    print(i,j)
    time.sleep(5)
    try:
        first_job_xpath = "/html/body/div[1]/div/div/div[3]/div/div/div[2]/section/ul/li["+str(j)+"]/div[1]/div/div/h3/a" #city ka path change karna cloudera ke saath

        # Wait for the first job to be clickable
        WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, first_job_xpath)))

            # Find the first job element and click on it
        first_job = driver.find_element(By.XPATH, first_job_xpath)
        first_job.click()
    except Exception as e:
        continue
    finally:
        print("Clicking on job was successful")


    time.sleep(5)
    print(driver.current_url)

  
#IDHAR APPLY_JOBS(i) PASS KARNE HAI
    apply_job(i)
    print(i)
    
    driver.quit()