import re
import time
from selenium_toolbox.buster_captcha_solver.buster_captcha_solver import buster_captcha_solver
from seleniumwire import webdriver
#import seleniumwire.undetected_chromedriver as webdriver
# A package to have a chromedriver always up-to-date.
from webdriver_manager.chrome import ChromeDriverManager


def proxy_options(method, host, port, user = None, password = None):
    if user != None and password != None:
        authetication = f"{user}:{password}@"
    elif user == None and password == None:
        authetication = ""
    else:
        raise ValueError("Proxy credentials are missing")

    if method == "http" or "https":
        method = ["http", "https"]
    elif method == "socks5":
        method = ["socks5", "socks5"]

    options = {
        "proxy": {
            "http": f"{method[0]}://{authetication}{host}:{port}",
            "https": f"{method[1]}://{authetication}{host}:{port}",
            'no_proxy': 'localhost,127.0.0.1'
        }
    }
    return options


def get_driver(dir = "chrome_extension", image = True, proxy = None):
    options = webdriver.ChromeOptions()
    seleniumwire_options = None
    # options.headless = True

    if proxy:
        try:
            if "@" in proxy:
                str = re.match(r'(.*)://(.*):(.*)@(.*):(.*)', proxy)
                method = str.group(1)
                user = str.group(2)
                pwd = str.group(3)
                host = str.group(4)
                port = str.group(5)
                seleniumwire_options = proxy_options(method, user, pwd, host, port)
            else:
                str = re.match(r'(.*)://(.*):(.*)', proxy)
                method = str.group(1)
                host = str.group(2)
                port = str.group(3)
                seleniumwire_options = proxy_options(method, host, port)
        except:
            raise ValueError("Invalid Proxy, use format: method://user:pwd@host:port")

    # Download Buster Captcha Solver
    extn_1 = buster_captcha_solver(dir, unzip=True)
    # Load extensions
    options.add_argument(f"--load-extension={extn_1}")

    # Disable images
    if image == False:
        prefs = {"profile.managed_default_content_settings.images": 2}
        options.add_experimental_option("prefs", prefs)

    driver = webdriver.Chrome(
        ChromeDriverManager().install(), options=options, seleniumwire_options=seleniumwire_options)

    return driver

if __name__ == "__main__":
    driver = get_driver(proxy = "http://192.168.10.100:8888")
    driver.get("https://apple.com")
    time.sleep(10)