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
from ldt.ldt_utils.models import Content, Project, Media, Author
import ldt.indexation
from guardian.admin import GuardedModelAdmin

class ProjectAdmin(GuardedModelAdmin):
    pass

admin.site.register(Project, ProjectAdmin)

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 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")
        )
        return content_urls + urls


admin.site.register(Content, ContentAdmin)
admin.site.register(Media)
admin.site.register(Author)