import logging
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

from athenaidx.config import Config

class HTB:
    def __init__(self, config: Config):
        self.driver = config.driver
        
    def _get_htb_options(self):
        WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.ID, "htb-context-bar"))
        )
        options = self.driver.find_elements(By.CLASS_NAME, 'htb-menu-item')       
        return [option.text for option in options]
    
    def _confirm_htb_selection(self, option_name: str) -> bool:
        selected_option = self.driver.find_element(By.CLASS_NAME, 'rcm-button.fe_c_button.selected')
        return selected_option.text == option_name

    def select_htb_option(self, option_name: str):
        if option_name not in self._get_htb_options():
            logging.error(f"Option '{option_name}' not found in HTB.")
            return
        
        if self._confirm_htb_selection(option_name):
            logging.info(f"Option '{option_name}' is already selected in HTB.")
            return
        
        try:
            options = self.driver.find_elements(By.CLASS_NAME, 'htb-menu-item')
            option_element = next((opt for opt in options if opt.text == option_name), None)
            if not option_element:
                logging.error(f"Option '{option_name}' not found in HTB.")
                return
            option_element.click()
            time.sleep(1)
            if not self._confirm_htb_selection(option_name):
                logging.error(f"Failed to select option '{option_name}'.")
        except Exception as e:
            logging.error(f"An error occurred while selecting option '{option_name}': {e}")
    
    def select_payment_posting(self):
        self.select_htb_option("Payment Posting")