from django.conf.urls.defaults import patterns, url
from django.contrib import admin
from django.shortcuts import render_to_response
from django.template import RequestContext
from ldt.ldt_utils.contentindexer import ContentIndexer, ProjectIndexer
from ldt.ldt_utils.fileimport import FileImport, FileImportError
from ldt.ldt_utils.forms import LdtImportForm, ReindexForm, StatAnnotationForm
from ldt.ldt_utils.models import Content, Project, Media, Author, AnnotationStat
import ldt.indexation
from guardian.admin import GuardedModelAdmin


class StatInlineAdmin(admin.TabularInline):
    model = AnnotationStat
    extra = 1

class ProjectAdmin(GuardedModelAdmin):
    inlines = [StatInlineAdmin, ]

class AuthorAdmin(GuardedModelAdmin):
    pass

class MediaAdmin(GuardedModelAdmin):
    pass

class ContentAdmin(GuardedModelAdmin):
    
    def import_file(self, request):
        if request.method == 'POST':
            form = LdtImportForm(request.POST, request.FILES)
            if form.is_valid():
                filetoprocess = form.cleaned_data['importFile']
                flatten = form.cleaned_data['flatten']
                videoPath = form.cleaned_data['videoPath']
                # fi = None
                fi = FileImport(filetoprocess, videoPath, flatten)
                try:
                    fi.process_file()
                    args = {'message': "File imported"}
                except FileImportError:
                    non_field_errors = form.non_field_errors()
                    non_field_errors.append("Error when importing : unknown file type")
                    form._errors["__all__"] = non_field_errors
                    args = {'message': "Can not import file, unknown file type", 'form': form}
                    
            else:
                non_field_errors = form.non_field_errors()
                non_field_errors.append("Error when importing : invalid form")
                form._errors["__all__"] = non_field_errors
                args = {'message': "Error when importing : invalid form", 'form': form}
        else:
            form = LdtImportForm()
            args = {'form': form, 'current_app': self.admin_site.name, 'current_action' : 'import_file'}
        return render_to_response('admin/ldt_utils/content/upload_form.html', args, context_instance=RequestContext(request))

    def reindex(self, request):
        message = None
        if request.method == "POST":
            form = ReindexForm(request.POST)
            if form.is_valid():    
                # try:
                writer = ldt.indexation.get_writer(True)
                try:
                    contentList = form.cleaned_data["contents"]
                    indexer = ContentIndexer(contentList, writer)
                    indexer.index_all()
                    
                    index_projects = form.cleaned_data["index_projects"]
                    if index_projects:
                        projectList = Project.objects.filter(contents__in=contentList, state=2).distinct() #filter(contents__in=contentList) @UndefinedVariable
                        indexer = ProjectIndexer(projectList, writer)
                        indexer.index_all()
                finally:
                    writer.close()
                message = "Indexation ok : " + repr(form.cleaned_data["contents"]) 
                form = ReindexForm()
                # except Exception, inst:
                    # non_field_errors = form.non_field_errors()
                    # non_field_errors.append("Error when reindexing : " + cgi.escape(repr(inst)))
                    # form._errors["__all__"] = non_field_errors
                    #message = "ERROR : " + repr(non_field_errors)
        else:
            form = ReindexForm()
    
        return render_to_response('admin/ldt_utils/content/reindex_form.html', {'form': form, 'message':message, 'current_app': self.admin_site.name, 'current_action' : 'reindex' }, context_instance=RequestContext(request))

    def stats_annotations(self, request):
        
        message = None
        if request.method == "POST":
            form = StatAnnotationForm(request.POST)
            
            if form.is_valid():
                
                if form.cleaned_data['choose_all']:
                    projects = Content.objects.all()
                else:
                    projects = form.cleaned_data['projects']
                
#                for content in contents:
#                    compute_stats_for(content)
                message = "Stats computed for :" + repr(projects)
        else:
            form = StatAnnotationForm()
            
        return render_to_response('admin/ldt_utils/content/stats_form.html', {'form': form, 'message':message, 'current_app': self.admin_site.name, 'current_action' : 'stats' }, context_instance=RequestContext(request))
            

    def get_urls(self):
        urls = super(ContentAdmin, self).get_urls()
        content_urls = patterns('',
            url(r'^reindex/$', self.admin_site.admin_view(self.reindex), name="ldt_content_reindex"),
    # (r'^admin/ldt/content/import/upload/$', 'ldt.ldt_utils.views.uploadFile'),                                
            url(r'^import/$', self.admin_site.admin_view(self.import_file), name="ldt_content_import_file"),
            url(r'^stats/$', self.admin_site.admin_view(self.stats_annotations), name="ldt_project_compute_stats")

        )
        
        return content_urls + urls


admin.site.register(Project, ProjectAdmin)
admin.site.register(Content, ContentAdmin)
admin.site.register(Media, MediaAdmin)
admin.site.register(Author, AuthorAdmin)
