from django.http import HttpResponse
from django.core.cache import cache
from EventSubscriptions.models import EventWithSubscriptions
import requests

'''
This view provides the final result requested from the exercise. It first looks for it in the cache; if the result is
not there, it calls the class "EventWithSubscriptions" in order to perform the query. If the response is successful,
is being stored inside the cache. Cache timeout is 4.2 minutes (252 seconds).
'''


def event_subscriptions(req):
    if req.method == 'GET':     # we process GET requests only
        if req.path.split('/')[2] == '':    # it is mandatory to insert characters for the event_id
            return HttpResponse("The path must be: \"/events-with-subscriptions/EVENT_ID\"")
        event_id = req.path.split('/')[2]
        key = 'event-with-subscriptions'
        timeout = 252   # cache timeout (4.2 minutes)
        result = cache.get(key)  # trying to get the result from the cache, otherwise => query to the website
        if result is None:
            obj = EventWithSubscriptions(event_id)
            result = obj.perform_and_combine_responses()
            # if the method gives us a response code or an Exception, we do not store the result in the cache
            if type(result) is int:
                return HttpResponse("Server returned with the following error code: " + str(result) +
                                    " . Please, try again later.")
            if type(result) is requests.Timeout:
                return HttpResponse("Connection timeout! Please, try again later")
            if type(result) is requests.RequestException:
                return HttpResponse("Problems with the network/server, please try again later.")
            cache.set(key, result, timeout)     # if the response is successful, setting the result in cache
        return HttpResponse(result, content_type='application/json')
    else:
        return HttpResponse("Unrecognized method")
