#!/usr/bin/env python3

# http://inamidst.com/saxo/
# Created by Sean B. Palmer

import re
import saxo

def one(arg):
    page = saxo.request("https://www.google.com/search",
                        query={"hl": "en", "q": arg}, modern=True)

    if "No results found for" in page["text"]:
        return "0"
    elif "did not match any documents" in page["text"]:
        return "0"

    regex_results = re.compile(r"(?i)([0-9,]+) results?")
    for result in regex_results.findall(page["text"]):
        if result:
            return result
    return "Sorry, there was an error"

def two(arg):
    page = saxo.request("https://www.google.co.uk/search", query={
        "ie": "UTF-8", "hl": "en-GB", "source": "hp",
        "q": arg, "btnG": "Google Search", "gbv": "1"})
    results = re.compile("About ([^ ]+) results")
    match = results.search(page["text"])
    if not match:
        return "0" # "No results found, sorry!"
    return arg + ": " + match.group(1)

def three(arg):
    import urllib
    import requests
    page = requests.get("https://text.brow.sh/" +
        "https://www.google.com/search?hl=en&q=%%22%s%%22" %
            urllib.parse.quote(arg),
        verify=False)
    if "did not match" in page.text:
        return "0"
    if "results" not in page.text:
        return "0"
    return page.text.split(" results").pop(0).rsplit(" ", 1).pop()

@saxo.pipe
def gc(arg):
    if not arg:
        return "Count the number of results for a phrase on Google"
    if arg.startswith(":one "):
        return one(arg.split(" ", 1).pop())
    if arg.startswith(":two "):
        return two(arg.split(" ", 1).pop())
    return three(arg)
