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

from athenaidx.config import Config

class VTB:
    VTB_TOGGLE = (By.ID, 'vtbToggleButton')
    VTB_OPTIONS_CONTAINER = (By.ID, 'vtbMenuContainer')
    
    def __init__(self, config:Config):
        self.driver = config.get_driver()
        
    def _check_vtb_status(self):
        try:
            vtb_toggle = WebDriverWait(self.driver, 2).until(
                EC.element_to_be_clickable(self.VTB_TOGGLE)
            )
            status = vtb_toggle.get_attribute('title')
            return status == 'Close Menu'
        except TimeoutException:
            logging.error("VTB toggle button not found.")
            return False
    
    def open_vtb(self):
        if not self._check_vtb_status():
            vtb_toggle = self.driver.find_element(*self.VTB_TOGGLE)
            vtb_toggle.click()
            time.sleep(1)
    
    def close_vtb(self):
        if self._check_vtb_status():
            vtb_toggle = self.driver.find_element(*self.VTB_TOGGLE)
            vtb_toggle.click()
            time.sleep(1)
    
    def _get_VTB_options(self):
        self.open_vtb()
        items = self.driver.find_elements(By.CSS_SELECTOR, 'div.vtb-items button')
        return [item.text for item in items]
    
    def _confirm_VTB_selection(self, option_name):
        # check if the button with the option name has a class of vtb-item selected
        selected_button = self.driver.find_element(By.XPATH, f"//button[contains(text(), '{option_name}')]")
        classes = selected_button.get_attribute('class')
        return 'selected' in classes.split() if classes else False
    
    def select_VTB_option(self, option_name):
        if option_name not in self._get_VTB_options():
            logging.error(f"Option '{option_name}' not available in VTB.")
            return
        self.open_vtb()
        option_xpath = f"//button[contains(text(), '{option_name}')]"
        try:
            option_element = WebDriverWait(self.driver, 5).until(
                EC.element_to_be_clickable((By.XPATH, option_xpath))
            )
            option_element.click()
            time.sleep(1)
            if not self._confirm_VTB_selection(option_name):
                logging.error(f"Failed to select option '{option_name}'.")
            self.close_vtb()
            time.sleep(1)
        except TimeoutException:
            logging.error(f"Option '{option_name}' not found in VTB.")
    
    def open_payment_posting(self):
        self.select_VTB_option('Payment Posting')
        