from tastypie.resources import ALL

from rhizome.api.resources.base_model import BaseModelResource
from rhizome.models import IndicatorTag


class IndicatorTagResource(BaseModelResource):
    '''
    **GET Request** Returns all indicator tags
        - *Optional Parameters:*
            'show_leaf'only return leaf level nodes of the indicator_tag tree
            'id' return the indicator_tag associated with the given id
        - *Errors:*

    **POST Request** Creates an indicator tag
        - *Required Parameters:*
            'tag_name'
        - *Optional Parameters:*
            'parent_tag_id'
        - *Errors:*
            if a required parameter is not supplied, the API will return a 500 error
    '''

    class Meta(BaseModelResource.Meta):
        GET_fields = ['id', 'parent_tag_id', 'tag_name', 'parent_tag__tag_name']
        object_class = IndicatorTag
        resource_name = 'indicator_tag'
        filtering = {
            'id': ALL,
            'tag_name': ALL,
            'parent_tag_id':ALL
        }
        required_fields_for_post = ['tag_name']

    def get_object_list(self, request):
        '''
        The 'show_leaf' parameter only shows the leaf level nodes of the tree.
        If that param is not requested, then we just return the base queryset
        from the parent_class.
        '''

        try:
            request.GET['show_leaf']
            all_parents = list(set(IndicatorTag.objects
                                   .filter(parent_tag_id__gt=0)
                                   .values_list('parent_tag_id', flat=True)))
            return IndicatorTag.objects.exclude(id__in=all_parents).values()
        except KeyError:
            return super(IndicatorTagResource, self).get_object_list(request)

@@ -1082,16 +1082,17 @@
 '%5D%0A%0A
+%0A
     def 
 get_
@@ -1091,239 +1091,69 @@
 def 
-get_object_list(self, request):%0A        '''%0A        The 'show_leaf' parameter only shows the leaf level nodes of the tree.%0A        If that param is not requested, then we just return the base queryset%0A        from the parent_class.
+apply_filters(self, request, applicable_filters):%0A        %22%22%22
 %0A   
@@ -1153,27 +1153,27 @@
 %22%22%22%0A        
-'''
+%22%22%22
 %0A%0A        tr
@@ -1229,94 +1229,27 @@
    a
-ll_parents = list(set(IndicatorTag.objects%0A                                   .
+pplicable_
 filter
-(
+s%5B'
 pare
@@ -1265,11 +1265,14 @@
 __gt
-=0)
+'%5D = 0
 %0A   
@@ -1280,232 +1280,62 @@
     
-                           .values_list('parent_tag_id', flat=True)))%0A            return IndicatorTag.objects.exclude(id__in=all_parents).values()%0A        except KeyError:%0A            return super(IndicatorTagResource,
+except KeyError:%0A            pass%0A%0A        return
  self
-)
 .get
@@ -1355,9 +1355,38 @@
 request)
+.filter(**applicable_filters)
 %0A

refactor indicator tag resource