# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/scraper/DriverGenerator.ipynb.

# %% auto 0
__all__ = ['DriverGenerator_NotInPath', 'DriverGenerator', 'DriverGeneratorLinux']

# %% ../../nbs/scraper/DriverGenerator.ipynb 2
import subprocess

from selenium import webdriver
from typing import Callable
import domolibrary_extensions.scraper.routes as desr

# %% ../../nbs/scraper/DriverGenerator.ipynb 5
class DriverGenerator_NotInPath(Exception):
    def __init__(self):
        super().__init__(
            "google-chrome not found in PATH and therefore cannot be accessed by a driver.  install it or add to PATH"
        )


class DriverGenerator:
    """
    crawler may request multiple drivers, so need a drivergenerator to spin up multiple
    class for generating drivers, can be extended for other drivers
    """

    driver_path: str = None
    authenticator_fn: Callable = (
        None  # if provided generated webdrivers will authenticate drivers
    )

    def __init__(self, driver_path=None, authenticator_fn: Callable = None):
        self.driver_path = driver_path
        self.authenticator_fn = authenticator_fn

    def get_webdriver(
        self,
        driver_path=None,
        is_headless: bool = True,
        authenticator_fn: Callable = None,
    ) -> webdriver:
        """create a chrome webdriver"""

        driver_path = driver_path or self.driver_path

        if not self.driver_path:
            self.driver_path = driver_path

        driver = desr.generate_webdriver(
            driver_path=driver_path, is_headless=is_headless
        )

        authenticator_fn = authenticator_fn or self.authenticator_fn
        if authenticator_fn:
            authenticator_fn(driver=driver)

        return driver

# %% ../../nbs/scraper/DriverGenerator.ipynb 7
class DriverGeneratorLinux(DriverGenerator):
    def __init__(self, driver_path, debug_prn: bool = False):
        self.driver_path = driver_path or "/usr//bin/chromedriver"

        assert self.is_chrome_in_path()

        if debug_prn:
            print(self.get_chromedriver_version())

        super().__init__()

    def is_chrome_in_path(self):
        result = subprocess.run(["which", "google-chrome"], stdout=subprocess.PIPE)
        is_chrome_in_path = result.stdout != b""

        if not is_chrome_in_path:
            raise DriverGenerator_NotInPath()

        return is_chrome_in_path

    def get_chromedriver_version(self):
        result = subprocess.run(["chromedriver", "--version"], stdout=subprocess.PIPE)
        return result.stdout.decode("utf-8")
