# Path: rtei/models.py
# class RteiDocument(AbstractDocument, index.Indexed):
#     '''A custom Document adding fields needed by RTEI Resource items.'''
# 
#     year = models.CharField(validators=[
#         RegexValidator(regex='^\d{4}$',
#                        message=_('Must be 4 numbers'),
#                        code='nomatch')],
#         help_text='e.g. 1999',
#         max_length=4,
#         blank=True)
# 
#     file = models.FileField(
#         upload_to='documents', verbose_name=_('file'), blank=True, null=True,
#         default='empty.txt',
#         help_text="Use this to upload a file and list it as a resource")
#     external_url = models.CharField(
#         validators=[URLValidator(message=_('Must be a valid URL'))],
#         blank=True,
#         max_length=1000,
#         verbose_name=_('External Link'),
#         help_text="Use this to add an external website as a listed resource")
#     country = models.CharField(max_length=256, blank=True)
#     is_resource = models.BooleanField(default=True,
#                                       help_text="Determines whether document "
#                                       "appears on the Resources page.")
#     description = RichTextField(blank=True)
# 
#     admin_form_fields = (
#         'title',
#         'description',
#         'file',
#         'external_url',
#         'collection',
#         'country',
#         'year',
#         'is_resource',
#         'tags'
#     )
# 
#     search_fields = AbstractDocument.search_fields + [
#         index.SearchField('title'),
#         index.SearchField('description'),
#         index.SearchField('country'),
#         index.SearchField('year'),
#         index.RelatedFields('tags', [
#             index.SearchField('name'),
#         ])
# 
#     ]
# 
#     class Meta:
#         get_latest_by = "created_at"
# 
# Path: rtei/data.py
# def get_countries_with_data():
#     year = settings.YEARS[-1]
#     scores_file = get_file_path('countries_with_data.json', year)
#     return get_json_file(scores_file)


from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from wagtail.core.models import Page
from wagtail.search.models import Query
from rtei.models import RteiDocument
from rtei.data import get_countries_with_data
        from itertools import chain


class CountryResult(object):

    def __init__(self, code, name):

        self.code = code
        self.name = name
        self.url = (reverse(
                            'wagtail_serve',
                            args=['explore/rtei-country/'])
                    + '?id=' + self.code)
        self.title = '{0}: {1}'.format(_('RTEI by Country'), self.name)


def search(request):
    search_query = request.GET.get('query', None)
    page = request.GET.get('page', 1)

    # Search
    if search_query:

        search_results_countries = []
        for code, name in get_countries_with_data().items():
            if name.lower().startswith(search_query.lower()):
                search_results_countries.append(CountryResult(code, name))

        search_results_pages = Page.objects.live().search(search_query)
        search_results_resources = RteiDocument.objects.search(search_query)


# Path: rtei/models.py
# class RteiDocument(AbstractDocument, index.Indexed):
#     '''A custom Document adding fields needed by RTEI Resource items.'''
# 
#     year = models.CharField(validators=[
#         RegexValidator(regex='^\d{4}$',
#                        message=_('Must be 4 numbers'),
#                        code='nomatch')],
#         help_text='e.g. 1999',
#         max_length=4,
#         blank=True)
# 
#     file = models.FileField(
#         upload_to='documents', verbose_name=_('file'), blank=True, null=True,
#         default='empty.txt',
#         help_text="Use this to upload a file and list it as a resource")
#     external_url = models.CharField(
#         validators=[URLValidator(message=_('Must be a valid URL'))],
#         blank=True,
#         max_length=1000,
#         verbose_name=_('External Link'),
#         help_text="Use this to add an external website as a listed resource")
#     country = models.CharField(max_length=256, blank=True)
#     is_resource = models.BooleanField(default=True,
#                                       help_text="Determines whether document "
#                                       "appears on the Resources page.")
#     description = RichTextField(blank=True)
# 
#     admin_form_fields = (
#         'title',
#         'description',
#         'file',
#         'external_url',
#         'collection',
#         'country',
#         'year',
#         'is_resource',
#         'tags'
#     )
# 
#     search_fields = AbstractDocument.search_fields + [
#         index.SearchField('title'),
#         index.SearchField('description'),
#         index.SearchField('country'),
#         index.SearchField('year'),
#         index.RelatedFields('tags', [
#             index.SearchField('name'),
#         ])
# 
#     ]
# 
#     class Meta:
#         get_latest_by = "created_at"
# 
# Path: rtei/data.py
# def get_countries_with_data():
#     year = settings.YEARS[-1]
#     scores_file = get_file_path('countries_with_data.json', year)
#     return get_json_file(scores_file)


# Path: search/views.py
from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from wagtail.core.models import Page
from wagtail.search.models import Query
from rtei.models import RteiDocument
from rtei.data import get_countries_with_data
        from itertools import chain



class CountryResult(object):

    def __init__(self, code, name):

        self.code = code
        self.name = name
        self.url = (reverse(
                            'wagtail_serve',
                            args=['explore/rtei-country/'])
                    + '?id=' + self.code)
        self.title = '{0}: {1}'.format(_('RTEI by Country'), self.name)


def search(request):
    search_query = request.GET.get('query', None)
    page = request.GET.get('page', 1)

    # Search
    if search_query:

        search_results_countries = []
        for code, name in get_countries_with_data().items():
            if name.lower().startswith(search_query.lower()):
                search_results_countries.append(CountryResult(code, name))

        search_results_pages = Page.objects.live().search(search_query)
        search_results_resources = RteiDocument.objects.search(search_query)


        search_results = list(chain(search_results_countries,