from django.conf.urls.defaults import url
from ldt.ldt_utils.models import Project
from ldt.api.ldt.authentication import SessionAuthentication
from ldt.api.ldt.serializers.cinelabserializer import CinelabSerializer
from ldt.api.ldt.resources import ContentResource
from ldt.api.ldt.resources.user import UserResource
from tastypie.authorization import Authorization
from tastypie.resources import Bundle, ModelResource, ALL
from tastypie import fields
from ldt.security import protect_models, unprotect_models

class ProjectResource(ModelResource):
    contents = fields.ManyToManyField(ContentResource, 'contents')
    owner = fields.ForeignKey(UserResource, 'owner')
    class Meta:
        allowed_methods = ['get', 'post']
        authorization = Authorization() # BE CAREFUL WITH THAT, it's unsecure
        authentication = SessionAuthentication()
        resource_name = 'projects'
        queryset = Project.objects.all()
        serializer = CinelabSerializer()
        filtering = {
            'state' : ALL,
            'ldt_id' : ALL
        }
        # In the future version :
        # detail_uri_name = 'ldt_id'
    
    
    def get_object_list(self, request):
        return Project.safe_objects.all()
    
    def override_urls(self):
        # WARNING : in tastypie <= 1.0, override_urls is used instead of prepend_urls. From 1.0.0, prepend_urls will be prefered and override_urls deprecated 
        return [
            url(r"^(?P<resource_name>%s)/(?P<ldt_id>[\w\d_.-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
        ]
    
    def get_resource_uri(self, bundle_or_obj):
        kwargs = {
            'resource_name': self._meta.resource_name,
            'api_name': self._meta.api_name
        }
        if isinstance(bundle_or_obj, Bundle):
            kwargs['ldt_id'] = bundle_or_obj.obj.ldt_id
        else:
            kwargs['ldt_id'] = bundle_or_obj.ldt_id
        return self._build_reverse_url("api_dispatch_detail", kwargs=kwargs)
    
    # TEMPORARY (used before authentication/authorization, because saving a project modifies a Content (via ContentStat))
    def save_m2m(self, bundle):
        unprotect_models()
        super(ProjectResource, self).save_m2m(bundle)
        protect_models()
    