#!/usr/bin/python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
import datetime
import keyring

# Init vars
now = datetime.datetime.now()


# uses the Apple KeyChain in OSX
# set these with `python -m keyring set kaleyra inaz_pass password`
username=""
password=""
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')  # Last I checked this was necessary.
driver = webdriver.Chrome('/usr/local/bin/chromedriver', options=options)
#driver.implicitly_wait(5) # gives an implicit wait for 20 seconds
def login(url, usernameId, username, passwordId, password, submit_buttonId):
    driver.get(url)
    wait(driver, 5).until(EC.frame_to_be_available_and_switch_to_it("FunArea"))
    driver.find_element_by_id(usernameId).send_keys(username)
    driver.find_element_by_id(passwordId).send_keys(password)
    driver.find_element_by_id(submit_buttonId).click()
def checklogin():
    # wait the ready state to be complete
    wait(driver=driver, timeout=10).until(
        lambda x: x.execute_script("return document.readyState === 'complete'")
    )
    error_message = "Login o Password errati"
    # get the errors (if there are)
    errors = driver.find_elements_by_class_name("TxtMsgErr")
    # print the errors optionally
    # for e in errors:
    #     print(e.text)
    # if we find that error message within errors, then login is failed
    f = open("/tmp/out.today", "w")
    if any(error_message in e.text for e in errors):
        f.write("[!] Login Failed!")
    else:
        today=now.strftime('%Y-%m-%d')
        f.write(today)
    f.close()


def stamp(stamp_buttonId):
   wait(driver, 5).until(EC.frame_to_be_available_and_switch_to_it("PrimMainArea"))
   driver.find_element_by_xpath('//*[@title="Entrata"]').click()
   #driver.find_element_by_id(stamp_buttonId).click()

login("https://serviziweb.inaz.it/HEPortaleKALEYRA/default.aspx", "login", username, "pwd", password, "CmdInvia")
checklogin()
stamp("TVentra")
