from ajax_select import register, LookupChannel
from members.models import *
from django.utils.html import escape

@register('member')
class MemberLookup(LookupChannel):

    model = Member
    
    def get_query(self, q, request):
        from django.db.models import Q

        args = []

        for word in q.split():
            args.append(Q(given_names__icontains=word) | Q(surname__icontains=word))

        if not args:
            return [] # No words in query (only spaces?)


        return Member.objects.filter(*args)

    def get_result(self, obj):
        """ result is the simple text that is the completion of what the person typed """
        return "%s %s" % (escape(obj.surname), escape(obj.given_names))

    def format_match(self, obj):
        """ (HTML) formatted item for display in the dropdown """
        return "%s %s" % (escape(obj.surname), escape(obj.given_names))

    def format_item_display(self, obj):
        """ (HTML) formatted item for displaying item in the selected deck area """
        return "%s %s" % (escape(obj.surname), escape(obj.given_names))

    def check_auth(self, request):
        #TODO: Actual authentication?
        #The whole request can be denied earlier, this just limits the AJAX lookup channel? Not sure tough
        return True
@@ -524,17 +524,57 @@
 r(*args)
+.order_by('surname', 'given_names')%5B:10%5D
 %0A
-
 %0A    def
@@ -706,63 +706,27 @@
 urn 
-%22%25s %25s%22 %25 (escape(obj.surname), escape(obj.given
+obj._get_full
 _name
-s)
+(
 )%0A%0A 
@@ -842,63 +842,27 @@
 urn 
-%22%25s %25s%22 %25 (escape(obj.surname), escape(obj.given
+obj._get_full
 _name
-s)
+(
 )%0A%0A 
@@ -1003,63 +1003,27 @@
 urn 
-%22%25s %25s%22 %25 (escape(obj.surname), escape(obj.given
+obj._get_full
 _name
-s)
+(
 )%0A%0A 

Refactor AJAX search to use member model methods