from serpapi import GoogleSearch
from backdev.settings import env

topics = [
    'Pandemic',
    'Extreme Weather',
    'Rising Temperatures',
    'Sea Level Rise',
    'Coastal Ecosystems',
    'Energy Consumption',
    'Sustainable Materials',
    'Recycling/Upcycling',
    'Green Technology',
    'Citizen Science',
    'Community Engagement'
]


def buildParams(topic):
    """
    Builds the params object for the request to SerpApi (https://serpapi.com/search-apietete) for a given topic (the keywords to be queried)

    Arguments:
        topic -- The topic to build the params for

    Returns:
        Dictionary - params object
    """
    return {
        'api_key': env('SERPAPI_TESTING_APIKEY') if env('DEBUG') else env('SERPAPI_APIKEY'),
        'engine': 'google',
        'q': topic + " miami",
        'location': 'Miami, Florida, United States',
        'google_domain': 'google.com',
        'gl': 'us',
        'hl': 'en',
        'tbm': 'nws'
    }


def fetchNews():
    """
    Fetches news from Miami from SerpApi. In development, it only runs if there are no News in the database.

    Returns:
        Boolean - Whether or not News were added to the database
    """
    try:
        from .models import News
        if News.objects.all() and env('DEBUG'):
            print(
                "There are news in the database and you are runnning in development mode. fetchNews will not run")
            return False
        articles = []
        for topic in topics:
            search = GoogleSearch(buildParams(topic))
            results = search.get_dict()
            articlesQueried = results["news_results"]
            for article in articlesQueried:
                articles.append(News(
                    title=article["title"],
                    url=article["link"],
                    source=article["source"],
                    date=article["date"],
                    community="Miami",
                    topic=topic
                ))
        if(not articles):
            return False
        News.objects.all().delete()
        News.objects.bulk_create(articles)
        return True
    except Exception as e:
        print(e)
        return False
