# Create your views here.
from core import settings
from django.http.response import HttpResponseNotFound, HttpResponse,\
    HttpResponseBadRequest
from django.views.generic import View
import requests
from requests.exceptions import HTTPError

class SparqlEndpointProxy(View):
    
    def get(self, request, wp_lang):
        params = request.GET.dict()
        if not wp_lang or wp_lang not in settings.WIKIPEDIA_URLS:
                return HttpResponseBadRequest("The wp_lang parameter is compulsory and must be in %s" % repr(settings.WIKIPEDIA_URLS.keys()))  # @UndefinedVariable

        url = settings.WIKIPEDIA_URLS.get(wp_lang, {}).get('dbpedia_sparql_url', None)  # @UndefinedVariable
        if not url or not url.startswith("http"):
            return HttpResponseNotFound("No or bad url for %s: %s" % (wp_lang,repr(url)))
        
        try:
            resp = requests.get(url, params=params)
            return HttpResponse(content=resp.text, content_type=resp.headers.get('content-type'))
        except HTTPError as e:
            return HttpResponse(unicode(e), status=e.status_code)
        
        
    