import os
import time
import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from PIL import Image
from io import BytesIO

# Configuration
url = 'https://publicgold.com.my/'
screenshot_dir = './screenshots/'
previous_data_file = './previous_data.txt'
chromedriver_path = '/path/to/chromedriver'  # Update this path

# Ensure screenshot directory exists
if not os.path.exists(screenshot_dir):
    os.makedirs(screenshot_dir)

# Function to capture screenshot
def capture_screenshot(filename):
    options = Options()
    options.headless = True
    service = Service(chromedriver_path)
    driver = webdriver.Chrome(service=service, options=options)

    driver.get(url)
    time.sleep(5)  # Wait for the page to load

    # Adjust the XPath as needed
    element = driver.find_element(By.XPATH, '//*[contains(@class, "col-md-12 col-xs-12")]')
    
    # Capture screenshot of the element
    element.screenshot(filename)
    driver.quit()

# Function to get current gold price and date
def get_current_data():
    response = requests.get(url)
    # Example using BeautifulSoup for parsing (if needed)
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(response.content, 'html.parser')
    
    # Adjust these selectors based on the actual HTML structure
    price_element = soup.select_one('.col-md-12.col-xs-12')
    current_price = price_element.get_text(strip=True)
    
    return current_price

# Function to check if data has changed
def check_for_changes():
    current_data = get_current_data()

    if os.path.exists(previous_data_file):
        with open(previous_data_file, 'r') as file:
            previous_data = file.read().strip()
    else:
        previous_data = ''

    if current_data != previous_data:
        timestamp = time.strftime('%Y%m%d_%H%M%S')
        screenshot_path = os.path.join(screenshot_dir, f'screenshot_{timestamp}.png')
        capture_screenshot(screenshot_path)

        with open(previous_data_file, 'w') as file:
            file.write(current_data)
        print(f"Data changed. Screenshot taken: {screenshot_path}")
    else:
        print("No change in data.")

# Run the check periodically
if __name__ == "__main__":
    check_for_changes()
