from contextlib import contextmanager
import time

from django.contrib.auth.models import User
from django.test import LiveServerTestCase

from selenium import webdriver
from selenium.common import exceptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support.expected_conditions import (
    staleness_of, visibility_of_element_located
)
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.select import Select

from apps.map.models import CaseStudy


TIMEOUT = 8


class SeleniumTest(LiveServerTestCase):
    @classmethod
    def setUpClass(cls):
        profile = webdriver.FirefoxProfile()
        profile.set_preference("dom.forms.number", False)
        cls.sl = webdriver.Firefox(profile)
        cls.sl.implicitly_wait(TIMEOUT)
        super(SeleniumTest, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        cls.sl.quit()
        super(SeleniumTest, cls).tearDownClass()

    def setUp(self):
        self.user = User.objects.create_superuser(username='test', password='test',
                                                  email='test@example.com')

    def _open(self, url):
        self.sl.get('%s%s' % (self.live_server_url, url))

    @contextmanager
    def wait_for_page_load(self, timeout=30):
        old_page = self.sl.find_element_by_tag_name('html')
        yield
        WebDriverWait(self.sl, timeout).until(
            staleness_of(old_page)
        )

    def _select_option(self, select, option, optgroup=''):
        if optgroup:
            optgroup = '/optgroup'
        self.sl.find_element_by_xpath(
            "//select[@id='%s']%s/option[text()='%s']" % (select, optgroup, option)
        ).click()


class MapTest(SeleniumTest):
    def setUp(self):
        self.case_study = CaseStudy(
            approved=True,
            entry_name='test',
            location='{"type": "Point", "coordinates": [0, 0]}',
            sector_of_economy='RN',
            positive_or_negative='P',
            country='NZ',
            area_of_land='100',
            land_ownership='PRI',
            location_context='URB',
            describe_ecosystem='test',
            project_status='EXSTNG',
            synopsis='test',
            full_description='test',
            media_coverage_mainstream='test',
            media_coverage_independent='test'
        )
        self.case_study.save()

    def test_map(self):
        self._open('/')
        WebDriverWait(self.sl, 5).until(
            visibility_of_element_located(
                (By.CSS_SELECTOR, '.hello--hide')
            )
        )
        self.sl.find_element_by_css_selector('.hello--hide').click()

        WebDriverWait(self.sl, 5).until(
            visibility_of_element_located(
                (By.CSS_SELECTOR, '.leaflet-marker-icon')
            )
        )
        self.sl.find_element_by_css_selector('.leaflet-marker-icon').click()

        details_link = self.sl.find_element_by_css_selector('.leaflet-popup-content a.btn')
        self.assertTrue(details_link.is_displayed())

        details_link.click()

        self.assertTrue(self.sl.current_url.endswith('case-study/test'))