from selenium import webdriver
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

from enum import Enum
import time

magnus = "http://192.168.2.56/mbilling/"
login = {
    'user' : 'root',
    'password' : 'NgtAtONgeRaFtsbu',
}

class Tarifa(Enum):
    ESTANDAR = 'Tarifa Estándar'
    EMPRESA = 'Tarifa Empresas'
    PLANA1000 = 'Bono PTV'
    PLANA2000 = 'Bono PTV'

def authenticate(driver : webdriver.Firefox):
    driver.get(magnus)
    WebDriverWait(driver,3).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="textfield-1013-inputEl"]'))).send_keys(login['user'])
    driver.find_element(By.XPATH,'//*[@id="textfield-1014-inputEl"]').send_keys(login['password'], Keys.ENTER)

    try:
        WebDriverWait(driver,5).until(EC.element_to_be_clickable((By.XPATH, ' //*[@id="tool-1031-toolEl"]'))).click()
    except TimeoutException:
        pass

def add_new_user(driver : webdriver.Firefox, telefono : str, tarifa : Tarifa = Tarifa.ESTANDAR):
    # Acceso a Panel 
    WebDriverWait(driver,3).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="treeview-1176-record-10"]'))).click()
    WebDriverWait(driver,3).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="button-1270"]'))).click()

    # Usuario
    username = WebDriverWait(driver,3).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="textfield-1291-inputEl"]')))
    username.clear()
    username.send_keys(telefono)
    driver.find_element(By.XPATH, '//*[@id="groupusercombo-1293-trigger-picker"]').click()
    driver.find_element(By.XPATH, '//ul[@data-ref="listEl"]/li[text()="Cliente"]').click()

    # Tarifa
    driver.find_element(By.XPATH, '//*[@id="button-1297"]').click()
    tarifa = WebDriverWait(driver,3).until(EC.element_to_be_clickable(
        (By.XPATH, f'//*[contains(@id,"tableview")]//table//div[text()="{tarifa.value}"]'))
    )
    ActionChains(driver).double_click(tarifa).perform()
    driver.find_element(By.XPATH, '//*[@id="button-1403"]').click()

    # Datos Personales
    driver.find_element(By.XPATH, '//*[@id="tab-1357-btnInnerEl"]').click()

    
if __name__ == '__main__':
    options = FirefoxOptions()
    #options.add_argument("--headless")
    driver = webdriver.Firefox(options=options)
    authenticate(driver)
    add_new_user(driver, '956367300')