import requests
from random import randint
from emailfinder.utils.exception import GoogleCaptcha, GoogleCookiePolicies
from emailfinder.utils.agent import user_agent
from emailfinder.utils.file.email_parser import get_emails
import urllib3
urllib3.disable_warnings()


def search(target, proxies=None, total=200):
	emails = set()
	start = 0
	num = 50 if total > 50 else total
	iterations = int(total/50)
	if (total%50) != 0:
		iterations += 1
	url_base = f"https://www.google.com/search?q=intext:@{target}&num={num}"
	cookies = {"CONSENT": "YES+srp.gws"}
	while start < iterations:
		try:
			url = url_base + f"&start={start}"
			response = requests.get(url, 
			# headers={'User-agent': 'APIs-Google (+https://developers.google.com/webmasters/APIs-Google.html)'},
			headers=user_agent.get(randint(0, len(user_agent)-1)),
			verify=False,
			allow_redirects=False,
			cookies=cookies)
			text = response.text
			if response.status_code == 302 and ("htps://www.google.com/webhp" in text or "https://consent.google.com" in text):
				raise GoogleCookiePolicies()
			elif "detected unusual traffic" in text:
				raise GoogleCaptcha()
			emails = emails.union(get_emails(target, text))
		except Exception as ex:
			raise ex #It's left over... but it stays there
		start += 1
	return list(emails)	