import logging

from selenium import webdriver
from selenium.webdriver import Chrome, ChromeOptions

# from msedge.selenium_tools.options import Options
# from msedge.selenium_tools import Edge
from selenium.common.exceptions import NoSuchElementException
import os
import pickle
import time
from colored import fg, attr
from uuid import uuid4
from random import randrange, choice

worker = None


class Worker(object):
    def __init__(
            self, username, password, cookie_name, port, headless=False, proxy=True
    ):
        self.username = username
        self.password = password
        self.cookie_name = cookie_name
        self.headless = headless
        self.driver = self.set_driver(headless, proxy, port)
        self.uuid = uuid4()
        self.fg = randrange(1, 7)
        self.attr = choice([0, 1, 4])

    def set_driver(self, headless, proxy, port) -> webdriver.Edge:
        logging.info(port)
        if os.path.isfile("webdrivers/chromedriver.exe"):
            chrome_driver = "webdrivers/chromedriver.exe"
        else:
            print("No driver found.")
            raise FileNotFoundError
        options = ChromeOptions()
        # options.add_argument('ignore-certificate-errors')
        options.add_argument("disable-web-security")
        # options.add_extension("data/webrtc.crx")

        if headless:
            options.headless = True

        capabilities = webdriver.DesiredCapabilities.CHROME.copy()
        if proxy:
            capabilities["proxy"] = {
                "httpProxy": f"192.168.1.52:{port}",
                "ftpProxy": f"192.168.1.52:{port}",
                "sslProxy": f"192.168.1.52:{port}",
                "proxyType": "MANUAL",
            }
        else:
            logging.warning("Not using proxy!")

        return Chrome(
            options=options,
            executable_path=chrome_driver,
            desired_capabilities=capabilities,
        )

    def login(self):
        self.driver.get("https://www.dickssportinggoods.com/")
        # driver = self.driver
        # driver.implicitly_wait(5)
        # driver.get("https://www.nike.com/login")
        # driver.find_element_by_css_selector("input[autocomplete='email']").send_keys(self.username)
        # driver.find_element_by_css_selector('input[autocomplete="current-password"]').send_keys(self.password)
        # driver.find_element_by_css_selector('input[value="SIGN IN"]').click()

        # success = False
        # while not success:
        #     time.sleep(2)
        #
        #     try:
        #         driver.implicitly_wait(1)
        #         driver.find_element_by_css_selector('input[value="Dismiss this error"]').click()
        #         driver.implicitly_wait(5)
        #         driver.find_element_by_css_selector('input[autocomplete="current-password"]').send_keys(self.password)
        #         driver.find_element_by_css_selector('input[value="SIGN IN"]').click()
        #     except:
        #         success = True
        # if driver.find_element_by_css_selector()

    def go(self):
        driver = self.driver
        driver.implicitly_wait(2)

        logging.info(f"Starting on thing")
        time.sleep(10000)

        logging.error("Uh oh, I made it too far!")

    def close(self):
        self.driver.close()
        self.driver.quit()

    @staticmethod
    def get_node_text(webElement):
        text: str = webElement.text
        for child in webElement.find_elements_by_xpath("./*"):
            text = text.replace(child.text, "")
        return text

    def print(self, string: str):
        print(
            f"{fg(self.fg)}{str(self.uuid)[:6]}--{string}{attr(self.attr)}", flush=True
        )

    def check_for_error(self, webElement):
        pass


def initializer(login_list, port_list, log_queue, log_config, level=logging.DEBUG):
    log_config(log_queue, level)
    logging.info("init-start")
    global worker
    port = port_list.pop()
    login_info = login_list.pop()
    worker = Worker(
        login_info["un"],
        login_info["pw"],
        login_info["name"],
        port,
        headless=False,
        proxy=True,
    )
    worker.login()
    logging.info("init-fin")


def start():
    global worker
    result = worker.go()
    if result:
        logging.info(f"Finished successfully! {result}")
    else:
        logging.warning(f"Failed! {result}")
    return result


def before_exit():
    global worker
    worker.close()


if __name__ == "__main__":
    username = os.getenv("USERNAME")
    password = os.getenv("PASSWORD")

    cdriver = Worker(username, password, headless=False)
    cdriver.login()

    cdriver.go("Tyler", "Menezes", "Washington")
    cdriver.go("Jacob", "Cover", "San Diego")
    cdriver.go("TJ", "Horner", "San Diego")
    cdriver.close()
