from django.conf.urls import url
from django.contrib.auth import get_user_model
from tastypie.resources import Bundle, ModelResource

User = get_user_model()

class UserResource(ModelResource):
    class Meta:
        allowed_methods = ['get']
        queryset =  User.objects.all()
        resource_name = 'users'
    
    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/(?P<username>[\w\d_.-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
        ]
    
    def get_resource_uri(self, bundle_or_obj=None, url_name='api_dispatch_list'):
        if bundle_or_obj is None:
            return super(UserResource, self).get_resource_uri(bundle_or_obj, url_name)
        kwargs = {
            'resource_name': self._meta.resource_name,
            'api_name': self._meta.api_name
        }
        if isinstance(bundle_or_obj, Bundle):
            kwargs['username'] = bundle_or_obj.obj.username
        else:
            kwargs['username'] = bundle_or_obj.username
        return self._build_reverse_url("api_dispatch_detail", kwargs=kwargs)