from django.contrib import admin
from django.conf.urls.defaults import *
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
from models import *
from forms import *
from fileimport import *
from ldt.ldt import STORE
from ldt.ldt import ANALYZER

import lucene

admin.site.register(Project)

class ContentAdmin(admin.ModelAdmin):
    
    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.processFile()
                    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/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 = lucene.IndexWriter(STORE, ANALYZER, True, lucene.IndexWriter.MaxFieldLength.UNLIMITED)
                contentList = form.cleaned_data["contents"]
                indexer = ContentIndexer(contentList,writer)
                indexer.index_all()

                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/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.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)
