"""
TBD
"""

__author__ = "Lukas Mahler"
__version__ = "0.0.3"
__date__ = "05.06.2021"
__email__ = "m@hler.eu"
__status__ = "Development"

# Standard
import os
import json

# Custom
from colorama import init, Fore, Style
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec


def find_driver():
    """ Check for chromedriver """
    chrome_driver = None

    try:
        chrome_driver = os.getcwd() + "\\chromedriver.exe"
        chrome_driver = chrome_driver.resolve()
        os.path.isfile(chrome_driver)
    except Exception as e:
        # print("[DEBUG] Chromedriver wasn't found in current working directory")
        pass
    try:
        chrome_driver = os.environ["PROGRAMFILES(x86)"] + r"\Google\Chrome\driver\chromedriver.exe"
        os.path.isfile(chrome_driver)
    except Exception as e:
        # print(r"[DEBUG] Chromedriver wasn't found under %PROGRAMFILES(x86)%\Google\Chrome\driver")
        pass

    if not os.path.isfile(chrome_driver):
        print("[ERROR] Couldn't find a Chromedriver, exiting...")
        exit()

    return chrome_driver


def driveroptions():
    # Headless Chrome
    chrome_options = Options()
    # chrome_options.add_argument("--headless")
    chrome_options.add_argument("--window-size=1920x1080")
    chrome_options.add_argument("--log-level=3")  # Fatal
    chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])
    chrome_options.add_argument("--User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                                "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36")

    return chrome_options


def set_local_storage(driver, key, value):
    driver.execute_script("window.localStorage.setItem('{}',{})".format(key, json.dumps(value)))


def main():

    init()
    url = 'https://353-iz.impfterminservice.de/impftermine/service?plz=20357'
    # test
    url = 'https://226-iz.impfterminservice.de/impftermine/service?plz=22457'

    chrome_driver = find_driver()
    chrome_options = driveroptions()

    driver = webdriver.Chrome(options=chrome_options, executable_path=chrome_driver)
    driver.get(url)

    print("Fix the fucking cookie banner")
    set_local_storage(driver, "ets-plz", "20357")
    set_local_storage(driver, "nfa-cookie-settings", {"essential": "true", "statistics": "false"})
    set_local_storage(driver, "nfa-show-cinfo-20201110-VP1246", "false")
    print("Reloading page...")

    driver.get(url)
    # print("[DEBUG] NOW AT:", driver.current_url)

    element_anspruchpruefen = WebDriverWait(driver, 10).until(
        ec.presence_of_element_located(
            (By.CSS_SELECTOR, ".ets-radio-control+ .ets-radio-control span")
        )
    )
    element_anspruchpruefen.click()

    txt = ""
    waiting = WebDriverWait(driver, 10).until_not(
        ec.text_to_be_present_in_element(
            (By.CSS_SELECTOR, ".in"), "Bitte warten"
        )
    )

    if not waiting:
        element = driver.find_element_by_css_selector(".in")
        txt = element.text

    if "keine freien Termine" in txt or txt == "":
        print(Fore.RED + "=> keine Termine" + Style.RESET_ALL)
        exit()
    else:
        print(Fore.GREEN + "=> Sieht gar nicht schlecht aus" + Style.RESET_ALL)

    element_impfberechtigt = WebDriverWait(driver, 10).until(
        ec.presence_of_element_located(
            (By.CSS_SELECTOR, ".align-items-start .ets-radio-control:nth-child(1) span")
        )
    )
    element_impfberechtigt.click()

    element_alter = WebDriverWait(driver, 10).until(
        ec.presence_of_element_located(
            (By.NAME, "age")
        )
    )

    element_alter.send_keys('26')
    element_alter.send_keys(Keys.ENTER)

    try:
        WebDriverWait(driver, 3).until(ec.url_changes(url))
    except TimeoutException:
        print(Fore.RED + "=> Doch keine Termine" + Style.RESET_ALL)
        exit()

    element_email = WebDriverWait(driver, 10).until(
        ec.presence_of_element_located(
            (By.CSS_SELECTOR, "input[formControlName=email]")
        )
    )
    element_email.send_keys('test@test.de')

    element_tel = driver.find_element_by_css_selector("input[formControlName=phone]")
    element_tel.send_keys('000000000000')

    url = driver.current_url
    element_tel.send_keys(Keys.ENTER)

    try:
        WebDriverWait(driver, 3).until(ec.url_changes(url))
    except TimeoutException:
        print(Fore.RED + "=> Anforderung fehlgeschlagen" + Style.RESET_ALL)
        exit()

    print(Fore.GREEN + "=> Buchung möglich, bitte Pin übergeben" + Style.RESET_ALL)

    # TODO
    # Benachrichtigung das eine Buchung durchgeführt werden kann
    # Irgendwie muss die PIN nun innerhalb von 10 Minuten vom Handy zur Website
    pin = input("Bitte Pin eingeben: ")

    element_pin = WebDriverWait(driver, 10).until(
        ec.presence_of_element_located(
            (By.CSS_SELECTOR, "input[formControlName=pin]")
        )
    )
    element_pin.send_keys(pin)

    # Wait Hack, delete on production
    input()

    # Cleanup
    driver.close()


if __name__ == "__main__":
    main()