# coding=utf-8
import re
from selenium import webdriver
import time



class ImmobilierStatistiquesScraper():
	def __init__(self):
		self.url = "https://immobilier.statistiques.notaires.fr/prix-immobilier"
		
	'''
	This function extracts the prix per m2 for a defined square and housing type
	'''
	def search_sqr(self, square, type_hab):
		driver = webdriver.Chrome('./resources/chromedriver')
		driver.implicitly_wait(2)
		driver.maximize_window()
		driver.get(self.url)

		# There is cookies information message which could provoke 'clicks' errors, so we are going to disble it
		driver.find_element_by_xpath('//a[@href="javascript:tagAnalyticsCNIL.CookieConsent.showInform()"]').click()
		time.sleep(1)
		driver.find_elements_by_name('cancel')[0].click()
		time.sleep(1)
		#Send keyboard input to the search box
		driver.find_element_by_xpath("//input[@type='search']").send_keys(square)
		# Choise an option in the dropdown menu appeared after send_keys
		# source: https://stackoverflow.com/questions/55796381/click-drop-down-menu-with-selenium-in-python
		driver.find_element_by_xpath("//ul[contains(@id, 'ui-select-choices-0')]").click()
		# Choise a housing type
		driver.find_element_by_xpath("//button[contains(@class, 'btn dropdown-toggle')]").click()
		# Looking for the corresponding option for housing type in the drop-down menu
		driver.find_element_by_xpath("//li[@class='ng-scope']//a[@class='{}']".format(type_hab)).click()
		driver.find_elements_by_xpath("//button[contains(text(), 'Rechercher')]")[0].click()
		time.sleep(2)
		# Getting the element which contains the mean prix per m2
		element = driver.find_elements_by_class_name('prix')
		html = element[0].get_attribute('innerHTML')
		driver.quit()

		return html