from django.views.generic import TemplateView
from .conf import settings
import logging
import requests

"""
The main search display view
"""


class SearchView(TemplateView):
    template_name = "googlesearch/google_search.html"

    @property
    def endpoint(self):
        return "https://www.googleapis.com/customsearch/%s/" % (
            settings.GOOGLE_SEARCH_API_VERSION)

    def get_context_data(self, **kwargs):

        context = super(SearchView, self).get_context_data(**kwargs)

        if len(self.request.GET) == 0:
            return context

        json = self.get_results(self.request.GET)

        if json is False:
            return context

        current_page = self.request.GET.get('page', 1)

        try:
            prev_page = json.queries.previousPage[0].startIndex
        except:
            prev_page = 1

        try:
            next_page = json.queries.nextPage[0].startIndex
        except:
            next_page = self.request.GET.get('page', 1)

        try:
            items = json.items
        except:
            items = []

        context.update({
            'items': items,
            'total_results': int(json.queries.request[0].totalResults),
            'current_page': int(current_page),
            'prev_page': int(prev_page),
            'next_page': int(next_page),
            'search_terms': json.queries.request[0].searchTerms,
        })

        return context

    """
    Makes the request to Google and returns
    matching pages in json
    """
    def get_results(self, GET):

        params = {
            'key': settings.GOOGLE_SEARCH_API_KEY,
            'q': GET.get('q', '').replace(' ', '+'),
            'cx': settings.GOOGLE_SEARCH_ENGINE_ID,
            'start': int(GET.get('page', 1)),
            'alt': 'json',
            'num': settings.GOOGLE_SEARCH_RESULTS_PER_PAGE,
            'sort': GET.get('sort', 'date-sdate:d:s')
        }

        try:
            r = requests.get(self.endpoint, params=params)

        except Exception as e:
            logging.warning("Google Custom Search Error: %s" % (str(e)))
            return False

@@ -501,361 +501,268 @@
     
-if len(self.request.GET) == 0:%0A            return context%0A%0A        json = self.get_results(self.request.GET)%0A%0A        if json is False:%0A            return context%0A%0A        current_page = self.request.GET.get('page', 1)%0A%0A        try:%0A            prev_page = json.queries.previousPage%5B0%5D.startIndex%0A        except:%0A            prev_page = 1%0A%0A        try:%0A
+cse_data = self.get_results(self.request.GET)%0A%0A        if cse_data and 'queries' in cse_data:%0A%0A            current_page = self.request.GET.get('page', 1)%0A%0A            if 'nextPage' in cse_data%5B'queries'%5D:%0A                # Super fragile lets hope it works%0A    
     
@@ -785,29 +785,37 @@
 e = 
-json.
+cse_data%5B'
 queries
-.
+'%5D%5B'
 nextPage
 %5B0%5D.
@@ -810,20 +810,23 @@
 nextPage
+'%5D
 %5B0%5D
-.
+%5B'
 startInd
@@ -827,25 +827,28 @@
 artIndex
-%0A
+'%5D%0A 
         
 except:%0A
@@ -835,32 +835,37 @@
 '%5D%0A         
-except:%0A
+   else:%0A    
             
@@ -921,82 +921,301 @@
     
-try:%0A            items = json.items%0A        except:%0A            items =
+    if 'previousPage' in cse_data%5B'queries'%5D:%0A                # Super fragile lets hope it works%0A                prev_page = cse_data%5B%0A                    'queries'%5D%5B'previousPage'%5D%5B0%5D%5B'startIndex'%5D%0A            else:%0A                prev_page = 0%0A%0A            items = cse_data.get('items',
  %5B%5D
+)
 %0A%0A  
@@ -1216,24 +1216,28 @@
 %5D)%0A%0A        
+   
+ 
 context.upda
@@ -1253,16 +1253,20 @@
         
+    
 'items':
@@ -1285,16 +1285,20 @@
         
+   
+ 
 'total_r
@@ -1314,32 +1314,64 @@
 int(
-json.
+%0A                    cse_data%5B'
 queries
-.
+'%5D%5B'
 request
+'%5D
 %5B0%5D
-.
+%5B'
 tota
@@ -1378,19 +1378,25 @@
 lResults
+'%5D
 ),%0A
+    
         
@@ -1426,32 +1426,36 @@
 (current_page),%0A
+    
             'pre
@@ -1491,16 +1491,20 @@
         
+    
 'next_pa
@@ -1536,16 +1536,20 @@
         
+    
 'search_
@@ -1560,57 +1560,443 @@
 s': 
-json.
+cse_data%5B%0A                    '
 queries
-.
+'%5D%5B'
 request
+'%5D
 %5B0%5D
-.
+%5B'searchTerms'%5D%0A            %7D)%0A%0A            return context%0A%0A        else:%0A%0A            context.update(%7B%0A                'items': %5B%5D,%0A                'total_results': 0,%0A                'current_page': 0,%0A                'prev_page': 0,%0A                'next_page': 0,%0A                '
 search
-T
+_t
 erms
-,%0A        %7D)%0A%0A
+': self.request.GET.get('q'),%0A                'error': cse_data%0A            %7D)%0A%0A    
     

Make view less fragile.