import os
from datetime import datetime
from pathlib import Path

import pytest
from notifications_python_client import NotificationsAPIClient
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

from config import config, setup_shared_config
from tests.pages.pages import HomePage
from tests.pages.rollups import sign_in, sign_in_email_auth


@pytest.fixture(scope="session", autouse=True)
def shared_config():
    """
    Setup shared config variables (eg env and urls)
    """
    setup_shared_config()


@pytest.fixture(scope="module")
def _driver():
    driver_name = (os.getenv('SELENIUM_DRIVER') or 'chrome').lower()
    if os.environ.get('TRAVIS'):
        driver_name = 'firefox'

    http_proxy = os.getenv('HTTP_PROXY')

    if driver_name == 'firefox':
        profile = webdriver.FirefoxProfile()
        profile.set_preference("general.useragent.override", "Selenium")

        if http_proxy is not None and http_proxy != "":
            http_proxy_url = http_proxy.split(':')[0] + ':' + http_proxy.split(':')[1]
            http_proxy_port = int(http_proxy.split(':')[2])
            profile.set_preference("network.proxy.type", 5)
            profile.set_preference("network.proxy.http", http_proxy_url)
            profile.set_preference("network.proxy.http_port", http_proxy_port)
            profile.set_preference("network.proxy.https", http_proxy_url)
            profile.set_preference("network.proxy.https_port", http_proxy_port)
            profile.set_preference("network.proxy.ssl", http_proxy_url)
            profile.set_preference("network.proxy.ssl_port", http_proxy_port)
            profile.update_preferences()

        binary = FirefoxBinary(log_file=open("./logs/browser.log", "wb"))
        driver = webdriver.Firefox(profile, firefox_binary=binary)
        driver.set_window_position(0, 0)
        driver.set_window_size(1280, 720)

    elif driver_name == 'chrome':
        options = webdriver.chrome.options.Options()
        options.add_argument("--no-sandbox")
        options.add_argument("--headless")
        options.add_argument("user-agent=Selenium")

        if http_proxy is not None and http_proxy != "":
            options.add_argument('--proxy-server={}'.format(http_proxy))

        service = ChromeService(log_path='./logs/chrome_browser.log', service_args=['--verbose'])

        driver = webdriver.Chrome(service=service, options=options)
        driver.set_window_size(1280, 720)

    else:
        raise ValueError('Invalid Selenium driver', driver_name)

    driver.delete_all_cookies()

    # go to root page and accept analytics cookies to hide banner in all pages
    driver.get(config['notify_admin_url'])
    HomePage(driver).accept_cookie_warning()
    yield driver
    driver.delete_all_cookies()
    driver.close()


@pytest.fixture(scope='function')
def driver(_driver, request):
    prev_failed_tests = request.session.testsfailed
    yield _driver
    if prev_failed_tests != request.session.testsfailed:
        print('URL at time of failure:', _driver.current_url)
        filename_datetime = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
        filename = str(Path.cwd() / 'screenshots' / '{}_{}.png'.format(filename_datetime, request.function.__name__))
        _driver.save_screenshot(str(filename))
        print('Error screenshot saved to ' + filename)


@pytest.fixture(scope="module")
def login_user(_driver):
    sign_in_email_auth(_driver)


@pytest.fixture(scope="module")
def login_seeded_user(_driver):
    sign_in(_driver, account_type='seeded')


@pytest.fixture(scope="module")
def client():
    client = NotificationsAPIClient(
        base_url=config['notify_api_url'],
        api_key=config['service']['api_key']
    )
    return client


@pytest.fixture(scope="module")
def seeded_client():
    client = NotificationsAPIClient(
        base_url=config['notify_api_url'],
        api_key=config['service']['api_live_key']
    )
    return client


@pytest.fixture(scope="module")
def seeded_client_using_test_key():
    client = NotificationsAPIClient(
        base_url=config['notify_api_url'],
        api_key=config['service']['api_test_key']
    )
    return client

@@ -241,76 +241,8 @@
 vice
-%0Afrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary
 %0A%0Afr
@@ -606,1357 +606,46 @@
     
-driver_name = (os.getenv('SELENIUM_DRIVER') or 'chrome').lower()%0A    if os.environ.get('TRAVIS'):%0A        driver_name = 'firefox'%0A%0A    http_proxy = os.getenv('HTTP_PROXY')%0A%0A    if driver_name == 'firefox':%0A        profile = webdriver.FirefoxProfile()%0A        profile.set_preference(%22general.useragent.override%22, %22Selenium%22)%0A%0A        if http_proxy is not None and http_proxy != %22%22:%0A            http_proxy_url = http_proxy.split(':')%5B0%5D + ':' + http_proxy.split(':')%5B1%5D%0A            http_proxy_port = int(http_proxy.split(':')%5B2%5D)%0A            profile.set_preference(%22network.proxy.type%22, 5)%0A            profile.set_preference(%22network.proxy.http%22, http_proxy_url)%0A            profile.set_preference(%22network.proxy.http_port%22, http_proxy_port)%0A            profile.set_preference(%22network.proxy.https%22, http_proxy_url)%0A            profile.set_preference(%22network.proxy.https_port%22, http_proxy_port)%0A            profile.set_preference(%22network.proxy.ssl%22, http_proxy_url)%0A            profile.set_preference(%22network.proxy.ssl_port%22, http_proxy_port)%0A            profile.update_preferences()%0A%0A        binary = FirefoxBinary(log_file=open(%22./logs/browser.log%22, %22wb%22))%0A        driver = webdriver.Firefox(profile, firefox_binary=binary)%0A        driver.set_window_position(0, 0)%0A        driver.set_window_size(1280, 720)%0A%0A    elif driver_name == 'chrome':%0A    
+http_proxy = os.getenv('HTTP_PROXY')%0A%0A
     
@@ -689,20 +689,16 @@
 tions()%0A
-    
     opti
@@ -730,20 +730,16 @@
 ndbox%22)%0A
-    
     opti
@@ -769,28 +769,24 @@
 dless%22)%0A    
- 
-   
 options.add_
@@ -822,20 +822,16 @@
 %22)%0A%0A    
-   
- 
 if http_
@@ -870,20 +870,16 @@
  != %22%22:%0A
-    
         
@@ -940,20 +940,16 @@
 roxy))%0A%0A
-    
     serv
@@ -1035,20 +1035,16 @@
 ose'%5D)%0A%0A
-    
     driv
@@ -1103,20 +1103,16 @@
 ns)%0A    
-   
- 
 driver.s
@@ -1142,84 +1142,8 @@
 0)%0A%0A
-    else:%0A        raise ValueError('Invalid Selenium driver', driver_name)%0A%0A
     

Remove Firefox set-up