from appium import webdriver
from appium.options.ios import XCUITestOptions
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

options = XCUITestOptions()
options.automation_name = 'XCUITest'

# Unique to device
options.udid = '00008120E2B0B8724249DA6D' # UDID
options.device_name = "appium-demo" # Name
options.platform_name = 'iOS'
options.platform_version = '18.3.1' # iOS version

# WDA settings
options.set_capability('webDriverAgentUrl', 'http://10.11.1.1:8100') # Services IP of Corellium device
options.set_capability('usePreinstalledWDA', True)
options.set_capability('updatedWDABundleId', 'org.appium.WebDriverAgentRunner') # From Xcode project
options.set_capability('updatedWDABundleIdSuffix', '.xctrunner')

# App settings
options.bundle_id = 'com.facebook.Facebook' # Bundle ID of target application
options.set_capability('autoAcceptAlerts', True) # Automatically accepts permission requests

try:
    driver = webdriver.Remote('http://127.0.0.1:4723', options=options)
    print("Connected to Facebook")

    wait = WebDriverWait(driver, 60)

    email_field = wait.until(
        EC.presence_of_element_located((AppiumBy.ACCESSIBILITY_ID, "Mobile number or email"))
    )
    email_field.send_keys("danyaal@tfp0labs.com")
    print("Entered email")

    password_field = wait.until(
        EC.presence_of_element_located((AppiumBy.ACCESSIBILITY_ID, "Password"))
    )
    password_field.send_keys("huz*myn9ncf0uqk7ZTX")
    print("Entered password")

    login_button = wait.until(
        EC.presence_of_element_located((AppiumBy.ACCESSIBILITY_ID, "Log in"))
    )
    login_button.click()
    print("Clicked login button")

    # Wait to accept alert before clicking 'Not Now'
    time.sleep(10)

    save_button = wait.until(
        EC.presence_of_element_located((AppiumBy.ACCESSIBILITY_ID, "Not now"))
    )
    save_button.click()
    print("Clicked on 'Not Now'")

    post_button = wait.until(
        EC.presence_of_element_located((AppiumBy.ACCESSIBILITY_ID, "feed-inline-composer-button"))
    )
    post_button.click()
    print("Clicked on post field")

    post_field = wait.until(
        EC.presence_of_element_located((AppiumBy.ACCESSIBILITY_ID, "composer-text-view"))
    )
    post_field.click()

    # Find the field again to enter text (becomes stale after the first interaction)
    post_field = wait.until(
        EC.presence_of_element_located((AppiumBy.ACCESSIBILITY_ID, "composer-text-view"))
    )
    message = "Hello World!"
    post_field.click()
    post_field.send_keys(message)
    print(f"Sent '{message}' in post")

    publish_post = wait.until(
        EC.presence_of_element_located((AppiumBy.ACCESSIBILITY_ID, "composer-right-button"))
    ) 
    publish_post.click()
    print("Published post")

except Exception as e:
    print(f"Error occurred: {str(e)}")
    print(f"Error type: {type(e)}")