#!/usr/bin/python3

import os
import sys
import json
import time
import logging
import platform
import subprocess
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains

# Get the directory of the currently executing script
script_dir = os.path.dirname(os.path.realpath(sys.argv[0]))

# now we will Create and configure logger
log_file = os.path.join(script_dir, 'claim.log')
logging.basicConfig(filename=log_file,
                    format='%(asctime)s %(message)s',
                    datefmt='%d.%m.%Y %H:%M:%S',
                    filemode='w')

# Creates an object
logger = logging.getLogger()

# Set logging level
logger.setLevel(logging.INFO)

# Load username and password from JSON file
json_file = os.path.join(script_dir, 'honeygainlogin.json')

with open(json_file, 'r') as file:
    login_data = json.load(file)

username = login_data['username']
password = login_data['password']

# Set the path to the Chrome binary
# Determine the path to the Chrome binary based on the operating system
if platform.system() == 'Windows':
    chrome_binary = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
else:
    chrome_binary = '/usr/bin/google-chrome'

# Set the Chrome options to use the binary and run in headless mode
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])
chrome_options.binary_location = chrome_binary
chrome_options.add_argument('--headless')

"""
Start the ChromeDriver process with stdout
and stderr redirected to /dev/null or subprocess.DEVNULL
"""
if platform.system() == 'Windows':
    devnull = subprocess.DEVNULL
else:
    devnull = open('/dev/null', 'w')
process = subprocess.Popen(['/usr/local/bin/chromedriver'], stdout=devnull, stderr=devnull)

# Create a new Chrome driver using chromedriver and the Chrome options
driver = webdriver.Chrome(options=chrome_options)

# Set the window size to 2560x1440 pixels
driver.set_window_size(2560, 1440)

# Navigate to the login page
driver.get('https://dashboard.honeygain.com/login')

try:
    # Wait for the login button
    WebDriverWait(driver, 10).until(EC.presence_of_element_located(
        (By.XPATH, "//button[contains(., 'Login with email')]"))
    )
except TimeoutException:
    logger.error("Timeout: Failed to load page within 10 seconds")
    driver.quit()

# Find username and password fields and enter login credentials
username_field = driver.find_element(By.ID, 'email')
username_field.send_keys(username)

password_field = driver.find_element(By.ID, 'password')
password_field.send_keys(password)

time.sleep(3)

# logger.info("Login to Honeygain")

# Click the login button to submit the form
submit_button = driver.find_element(
    By.XPATH, "//button[contains(., 'Login with email')]"
    )
driver.execute_script("arguments[0].scrollIntoView(true);", submit_button)
submit_button.click()
actions = ActionChains(driver)
actions.move_to_element(submit_button).click().perform()

try:
    # Wait for the "Earned today" section to be present on the page
    WebDriverWait(driver, 10).until(EC.presence_of_element_located(
        (By.XPATH, "//div[contains(text(), 'Total earnings')]"))
    )
except TimeoutException:
    logger.error("Timeout: Failed to load page within 10 seconds")
    driver.quit()

# Click on Cookie Banner
cookie_button = driver.find_element(
    By.XPATH, "//button[contains(., 'Accept selected')]"
    )
cookie_button.click()

try:
    timer = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located(
            (By.CSS_SELECTOR, 'div.sc-cUEOzv.kryQIl.sc-hshgAP.jDPslO')))

    # If the countdown element is present, get the current time and print it
    current_time = driver.find_element(
        By.CSS_SELECTOR, 'p.sc-jOiSOi.jgbyVL'
        ).text
    logger.info("Nächster Pot Verfügbar in: %s", current_time)
except TimeoutException:
    # If the timer element is not present, click on the lucky pot button
    try:
        # Wait for the "Open Lucky Pot" button to be present on the page
        WebDriverWait(driver, 10).until(EC.presence_of_element_located(
            (By.XPATH, "//span[contains(text(), 'Open Lucky Pot')]"))
        )
        logger.info('Öffne den Luckypot')
        # Find the "Open Lucky Pot" button and click it
        lucky_pot_button = driver.find_element(
            By.XPATH,
            "//span[contains(text(), 'Open Lucky Pot')]/ancestor::button"
            )
        lucky_pot_button.click()
        logger.info('Glückwunsch! Ich habe für dich gerade den Lucky Pot geöffnet')
    except TimeoutException:
        logger.error("The 'Open Lucky Pot' button was not found. Exiting...")
        driver.quit()

# Close the browser window
driver.quit()

process.terminate()

# Close the /dev/null file on Unix/Linux
if not platform.system() == 'Windows':
    devnull.close()
