# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from blinkster import settings
import blinkster
from blinkster.ldt.forms import LdtImportForm
from blinkster.ldt.forms import LdtProjectImportForm
from blinkster.ldt.forms import SearchForm, LdtForm, reindexForm 
from blinkster.ldt.fileimport import *
from blinkster.ldt.models import Author, LdtProject, Content
from blinkster.ldt.utils import *
import django.core.urlresolvers
import django.utils.http
import blinkster.ldt.models
import blinkster.utils.zipfileext
import blinkster.utils.log
import xml.dom.minidom
import xml.dom.ext
import urllib
import base64
import cgi
from blinkster.ldt import STORE
from blinkster.ldt import ANALYZER
from string import Template
from Ft.Xml import MarkupWriter

def index(request, url):
    
    urlStr = settings.WEB_URL + django.core.urlresolvers.reverse("blinkster.ldt.views.init", args=['ldt', url])
    language_code = request.LANGUAGE_CODE[:2]
    
    return render_to_response('ldt/init_ldt.html', {'MEDIA_URL': settings.MEDIA_URL, 'colorurl': settings.MEDIA_URL + 'swf/ldt/pkg/color.xml', 'i18nurl': settings.MEDIA_URL + 'swf/ldt/pkg/i18n', 'language': language_code, 'baseurl': settings.MEDIA_URL + 'swf/ldt/', 'url': urlStr}, context_instance=RequestContext(request))

def indexProject(request, id):

    urlStr = settings.WEB_URL + django.core.urlresolvers.reverse("blinkster.ldt.views.init", args=['ldtProject', id])
    language_code = request.LANGUAGE_CODE[:2]
    
    return render_to_response('ldt/init_ldt.html', {'MEDIA_URL': settings.MEDIA_URL, 'colorurl': settings.MEDIA_URL + 'swf/ldt/pkg/color.xml', 'i18nurl': settings.MEDIA_URL + 'swf/ldt/pkg/i18n', 'language': language_code, 'baseurl': settings.MEDIA_URL + 'swf/ldt/', 'url': urlStr}, context_instance=RequestContext(request))
        


def searchIndex(request):
    
    sform = SearchForm(request.POST)
    
    
    queryStr = base64.urlsafe_b64encode(request.POST["search"].encode('utf8'))
    field = request.POST["field"]
    language_code = request.LANGUAGE_CODE[:2]
    #blinkster.utils.log.debug(str(form))
    #blinkster.utils.log.debug(str(sform.cleaned_data))
    #queryStr = django.utils.http.urlquote_plus(form.search)
    
    url = settings.WEB_URL + django.core.urlresolvers.reverse("blinkster.ldt.views.searchInit", args=[field, queryStr])
    return render_to_response('ldt/init_ldt.html', {'MEDIA_URL': settings.MEDIA_URL, 'colorurl': settings.MEDIA_URL + 'swf/ldt/pkg/color.xml', 'i18nurl': settings.MEDIA_URL + 'swf/ldt/pkg/i18n', 'language': language_code, 'baseurl': settings.MEDIA_URL + 'swf/ldt/', 'url': url}, context_instance=RequestContext(request))

def searchIndexGet(request, field, query):

    language_code = request.LANGUAGE_CODE[:2]
    url = settings.WEB_URL + django.core.urlresolvers.reverse("blinkster.ldt.views.searchInit", args=[field, query])
    return render_to_response('ldt/init_ldt.html', {'MEDIA_URL': settings.MEDIA_URL, 'colorurl': settings.MEDIA_URL + 'swf/ldt/pkg/color.xml', 'i18nurl': settings.MEDIA_URL + 'swf/ldt/pkg/i18n', 'language': language_code, 'baseurl': settings.MEDIA_URL + 'swf/ldt/', 'url': url}, context_instance=RequestContext(request))

def searchInit(request, field, query):
    
    ldtgen = blinkster.ldt.utils.LdtUtils()
    
    doc = ldtgen.generateInit([field, query], 'blinkster.ldt.views.searchLdt', 'blinkster.ldt.views.searchSegments')
    
    resp = HttpResponse(mimetype="text/xml")
    xml.dom.ext.PrettyPrint(doc, resp)
    return resp
    

def init(request, method, url):

    ldtgen = blinkster.ldt.utils.LdtUtils()
    
    doc = ldtgen.generateInit([url], 'blinkster.ldt.views.' + method, None)
    
    resp = HttpResponse(mimetype="text/xml")
    xml.dom.ext.PrettyPrint(doc, resp)
    return resp



def ldt(request, url):
    
    import Ft
    from Ft.Xml import MarkupWriter
    
    resp = HttpResponse(mimetype="text/xml")
    
    contentList = blinkster.ldt.models.Content.objects.filter(iri_id=url)
    
    ldtgen = blinkster.ldt.utils.LdtUtils()
    ldtgen.generateLdt(contentList, file=resp, title=contentList[0].title)
    
    return resp
    
def ldtProject(request, id):
    resp = HttpResponse(mimetype="text/xml")
    
    project = blinkster.ldt.models.LdtProject.objects.get(id=id)
    template = Template(project.ldt)
    resp.write(template.safe_substitute({'web_url':settings.WEB_URL, 'media_url':settings.MEDIA_URL, 'stream_url': settings.STREAM_URL}))
    
    return resp
    



def importFile(request):
    form = LdtImportForm() 
    return render_to_response('ldt/upload_form.html', {'form': form} , context_instance=RequestContext(request))

def importProjectFile(request):
    form = LdtProjectImportForm()
    return render_to_response('ldt/upload_project_form.html', {'form': form}, context_instance=RequestContext(request))

def searchForm(request):
    form = SearchForm()
    return render_to_response('ldt/search_form.html', {'form': form} , context_instance=RequestContext(request))


def uploadFile(request):
    importform = LdtImportForm(request.POST, request.FILES)
    if importform.is_valid():
        blinkster.utils.log.debug(request.FILES)
        blinkster.utils.log.debug(importform.cleaned_data['author'])
        fi = FileImport(request.FILES['importFile'], importform.cleaned_data['author'])
        fi.processFile()
        fi.close()
        return HttpResponse("File imported")
    else:
        return HttpResponse("Form non valid")

def uploadProjectFile(request):
    importForm = LdtProjectImportForm(request.POST, request.FILES)
    args = {}
    if importForm.is_valid():
        blinkster.utils.log.debug(request.FILES)
        blinkster.utils.log.debug(importForm.cleaned_data['author'])
        
        filetoprocess = request.FILES['importFile']
        fi = None
        if filetoprocess.name.endswith(".ldt"):
            fi = ProjectFileImport(filetoprocess, importForm.cleaned_data['author'])
        elif filetoprocess.name.endswith(".zip"):
            fi = ZipProjectFileImport(filetoprocess, importForm.cleaned_data['author'])
            
        if fi is not None:
            ids = fi.processFile()
            fi.close()
            args = {'message': "File imported and project id " + unicode(ids) + " created" }
        else:
            non_field_errors = importForm.non_field_errors()
            non_field_errors.append("Error when importing : unknown file type")
            importForm._errors["__all__"] = non_field_errors
            args = {'message': "Can not import file, unknown file type", 'form': importForm}
    else:
        non_field_errors = importForm.non_field_errors()
        non_field_errors.append("Error when importing : invalid form")
        importForm._errors["__all__"] = non_field_errors

        args = {'message': "Error when importing : invalid form", 'form': importForm}
        
    return render_to_response('ldt/upload_project_form.html', args, context_instance=RequestContext(request))


def searchLdt(request, field, query, edition=None):
    
    contentList = []
    resp = HttpResponse(mimetype="text/xml")
    queryStr = ""

    if query and len(query) > 0:        
        queryStr = base64.urlsafe_b64decode(query.encode("ascii")).decode("utf8")
        #queryStr = base64.urlsafe_b64decode(query.trim("="))
        searcher = blinkster.ldt.utils.LdtSearch()
        ids = {}
        
        for result in searcher.query(field, queryStr):
            ids[result["iri_id"]] = ""            

        id_list = ids.keys()
        
        if edition is not None:
            ids_editions = map(lambda t:t[0], filter(lambda id: id[0] is not None, Speak.objects.filter(session__day__edition=edition).order_by("session__start_ts", "order").values_list("content__iri_id")))            
            id_list = filter(lambda id: id in id_list, ids_editions)
            
        contentList = blinkster.ldt.models.Content.objects.filter(iri_id__in=id_list)        

            
    ldtgen = blinkster.ldt.utils.LdtUtils()
    ldtgen.generateLdt(contentList, file=resp, title=u"Recherche : " + queryStr)
    
    return resp


def searchSegments(request, field, query, edition=None):
    
    if query and len(query) > 0:
        searcher = blinkster.ldt.utils.LdtSearch()
        
        queryStr = base64.urlsafe_b64decode(query.encode("ascii")).decode("utf8")
        res = searcher.query(field, queryStr)
    else:
        res = []
        
    iri_ids = None
    
    if edition is not None:
        iri_ids = map(lambda t:t[0], filter(lambda id: id[0] is not None, Speak.objects.filter(session__day__edition=edition).order_by("session__start_ts", "order").values_list("content__iri_id")))

    doc = xml.dom.getDOMImplementation().createDocument(None, "iri", None)

    for resultMap in res:
        if iri_ids is None or resultMap['iri_id'] in iri_ids:
            elem = doc.createElement('seg')
            elem.setAttribute('idctt', resultMap['iri_id'])
            elem.setAttribute('idens', resultMap['ensemble_id'])
            elem.setAttribute('iddec', resultMap['decoupage_id'])
            elem.setAttribute('idseg', resultMap['element_id'])
            elem.setAttribute('idvue', "")
            elem.setAttribute('crit', "")
            doc.documentElement.appendChild(elem)

    return HttpResponse(doc.toprettyxml(encoding='utf-8'), mimetype="text/xml")

def downloadLdt(request):

    if request.method == "POST":
        edition_id = request.POST['edition']
        user = request.POST['author']
   
        #edition = Edition.objects.get(id=edition_id).event_date.year 
        edition = None
        resp = HttpResponse(mimetype="text/xml")
        resp['Content-Disposition'] = "attachment; filename=%s.ldt" % (edition,)
        ids = map(lambda t:t[0], filter(lambda id: id[0] is not None, Speak.objects.filter(session__day__edition=edition_id).order_by("session__start_ts", "order").values_list("content")))
        rawContentList = Content.objects.in_bulk(ids)
        contentList = map(lambda id: rawContentList[id], ids)
        
        ldtgen = blinkster.ldt.utils.LdtUtils()
        ldtgen.generateLdt(contentList, file=resp, author=user, title="ENMI %s" % edition, web_url=settings.WEB_URL, media_url=settings.MEDIA_BASE_URL)
    
        return resp


def exportForm(request):
    form = LdtForm()
    return render_to_response('ldt/export_form.html', {'form': form} , context_instance=RequestContext(request))

def reindex(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)
                writer.setMaxFieldLength(1048576)
                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('ldt/reindex_form.html', {'form': form, 'message':message}, context_instance=RequestContext(request))

def getXmlFromProjectList(request, projects):
    
    resp = HttpResponse(mimetype="text/xml")
    
    writer = MarkupWriter(resp, indent=u"yes")
    writer.startDocument()
    writer.startElement(u"iri", attributes={u"version": blinkster.VERSION_STR})
    writer.startElement(u"projects")
    
    for project in projects:
            writer.startElement(u"project", attributes={"id":unicode(project.id), "url":unicode(settings.WEB_URL + django.core.urlresolvers.reverse('blinkster.ldt.views.indexProject', args=[project.id]))})
            writer.startElement(u"authors")
            for author in project.authors.all():
                writer.startElement(u"author")
                writer.simpleElement(u"handle", content=unicode(author.handle))
                writer.simpleElement(u"firstname", content=unicode(author.firstname))
                writer.simpleElement(u"lastname", content=unicode(author.lastname))
                writer.simpleElement(u"email", content=unicode(author.email))
                writer.endElement(u"author")
            writer.endElement(u"authors")
            writer.endElement(u"project")
    
    writer.endElement(u"projects") #</projects>
    writer.endElement(u"iri") #</iri>
    
    return resp


def getProjectFromContentId(request, content_id):

    projects = LdtProject.objects.filter(contents__iri_id__in=[content_id]).distinct()
    
    return getXmlFromProjectList(request, projects)
    

def getProjectFromContentExternalId(request, content_id):

    projects = LdtProject.objects.filter(contents__external_id__in=[content_id]).distinct()
    
    return getXmlFromProjectList(request, projects)
    
    
