from django.conf.urls import url
from egonomy.models import Image, ImageMetadata, ImageInfo, Fragment
from tastypie import fields
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from tastypie.resources import ModelResource
import logging
from egonomy.api.resources.fragment import FragmentResource

logger = logging.getLogger(__name__)


class ImageMetadataResource(ModelResource):
    class Meta:
        allowed_methods = ['get']
        resource_name = 'metadata'
        queryset = ImageMetadata.objects.all()
        filtering = {
            'titre' : ALL,
        }


class ImageInfoResource(ModelResource):
    class Meta:
        allowed_methods = ['get']
        resource_name = 'info'
        queryset = ImageInfo.objects.all()


class ImageResource(ModelResource):
    
    metadata = fields.ForeignKey(ImageMetadataResource, 'metadata', full=True)
    info = fields.ForeignKey(ImageInfoResource, 'info', full=True)
    
    class Meta:
        allowed_methods = ['get']
        resource_name = 'images'
        queryset = Image.objects.select_related('info', 'metadata').all()
        filtering = {
            'metadata' : ALL_WITH_RELATIONS,
        }
        ordering = ['id']

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/fragments/$" % self._meta.resource_name, self.wrap_view('get_image_framents'), name="api_get_image_framents"),            
        ]
    
    def get_image_framents(self, request, **kwargs):
        self.method_check(request, allowed=['get'])
        
        frag_res = FragmentResource()
        fragments = [frag_res.full_dehydrate(frag_res.build_bundle(obj=f, request=request)) for f in Fragment.objects.filter(image=Image.objects.get(id=kwargs["pk"]))]
        object_list = {
            'fragments': fragments,
        }
        
        self.log_throttled_access(request)
        
        return  self.create_response(request, object_list)
        
            