import django.core.urlresolvers
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.core import serializers
from django.utils import simplejson
from fileimport import *
from forms import LdtImportForm, LdtAddForm, SearchForm, AddProjectForm, CopyProjectForm
from ldt.core.models import Owner
from models import *
from utils import *
from contentindexer import *
from projectserializer import *
from string import Template
from Ft.Xml import MarkupWriter
import cgi
import uuid
import base64
import lucene
import xml.dom
import xml.dom.ext
import xml.dom.minidom


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

def searchIndex(request):
    
    sform = SearchForm(request.POST)
    if sform.is_valid():
        search = sform.cleaned_data["search"]
    
    
        queryStr = base64.urlsafe_b64encode(search.encode('utf8'))
        field = request.POST["field"]
        language_code = request.LANGUAGE_CODE[:2]
    
        url = settings.WEB_URL + django.core.urlresolvers.reverse("ldt.ldt_utils.views.searchInit", args=[field, queryStr])
        return render_to_response('ldt/ldt_utils/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))
    else:
        resp = HttpResponse()
        resp.write("<html><head></head><body>Error : No result</body></html>");

def searchIndexGet(request, field, query):

    language_code = request.LANGUAGE_CODE[:2]
    url = settings.WEB_URL + django.core.urlresolvers.reverse("ldt.ldt_utils.views.searchInit", args=[field, query])
    return render_to_response('irisuser/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 = LdtUtils()
    
    doc = ldtgen.generateInit([field,query], 'ldt.ldt_utils.views.searchLdt', 'ldt.ldt_utils.views.searchSegments')
    
    resp = HttpResponse(mimetype="text/xml;charset=utf-8")
    xml.dom.ext.PrettyPrint(doc, resp)
    return resp

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")
        searcher = 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 = Content.objects.filter(iri_id__in=id_list)        

            
    ldtgen = 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 = 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;charset=utf-8")
    
@login_required         
def list_ldt(request):
    contents = Content.objects.all()
    try:
        owner = Owner.objects.get(user=request.user)
    except:
        return HttpResponseRedirect(settings.LOGIN_URL)
    ldtProjects = Project.objects.filter(owner=owner)
    context={
    'contents': contents,
    'ldtProjects': ldtProjects.reverse(),
    }
    return render_to_response('ldt/ldt_utils/ldt_list.html', context, context_instance=RequestContext(request))

def create_ldt_view(request):
    if request.method == "POST" :
        form = LdtAddForm(request.POST)
        if form.is_valid():
            user = request.user
            Project.create_project(title=form.cleaned_data['title'], user=user, contents=form.cleaned_data['contents'])
            return HttpResponseRedirect(reverse("ldt.ldt_utils.views.list_ldt"))
    else:
        form = LdtAddForm()
        contents = Content.objects.all()    
        return render_to_response('ldt/ldt_utils/create_ldt.html', {'contents': contents, 'form': form,'create_project_action':reverse(create_ldt_view)}, context_instance=RequestContext(request))
     
def created_ldt(request):
    return render_to_response('ldt/ldt_utils/done.html', context_instance=RequestContext(request))
    
def indexProject(request, id):

    urlStr = settings.WEB_URL + reverse("space_ldt_init", args=['ldtProject', id])
    posturl= settings.WEB_URL + reverse("ldt.ldt_utils.views.save_ldtProject")
    language_code = request.LANGUAGE_CODE[:2]
    
    ldt = get_object_or_404(Project, ldt_id=id)
    if ldt.state ==2: #published
        readonly = 'true'
    else:
        readonly = 'false'
    
    return render_to_response('ldt/ldt_utils/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, 'posturl': posturl, 'id': id, 'readonly': readonly}, context_instance=RequestContext(request))
    
def init(request, method, url):
    ldtgen = LdtUtils()

    doc = ldtgen.generateInit([url], 'ldt.ldt_utils.views.'+method, None)

    resp = HttpResponse(mimetype="text/xml")
    resp['Cache-Control']='no-cache, must-revalidate'
    resp['Pragma']='no-cache'
    xml.dom.ext.PrettyPrint(doc, resp)
    return resp
       
def ldtProject(request, id):
    resp = HttpResponse(mimetype="text/xml")
    resp['Cache-Control']='no-cache, must-revalidate'
    resp['Pragma']='no-cache'
    
    project = Project.objects.get(ldt_id=id)
    resp.write(project.ldt)
    return resp


def project_json_id(request, id):
    
    project = get_object_or_404(Project,ldt_id=id)

    return project_json(request, project)


def project_json_externalid(request, id):
        
    res_proj = get_list_or_404(Project.objects.order_by('-modification_date'),contents__external_id = id)
    
    return project_json(request, res_proj[0])



def project_json(request, project):

    mimetype = request.REQUEST.get("mimetype")
    if mimetype is None:
        mimetype = "application/json; charset=utf-8"
    else:
        mimetype = mimetype.encode("utf-8")
    if "charset" not in mimetype:
        mimetype += "; charset=utf-8" 
    resp = HttpResponse(mimetype=mimetype)
    resp['Cache-Control']='no-cache, must-revalidate'
    resp['Pragma']='no-cache'
    
    indent = request.REQUEST.get("indent")
    if indent is None:
        indent = settings.LDT_JSON_DEFAULT_INDENT
    else:
        indent = int(indent)
    
    callback = request.REQUEST.get("callback")
        
    ps = ProjectSerializer(project)
    project_dict = ps.serialize_to_cinelab()
    
    json_str = simplejson.dumps(project_dict, ensure_ascii=False, indent=indent)
    
    if callback is not None:
        json_str = "%s(%s)" % (callback,json_str)
    
    resp.write(json_str)

    return resp


def save_ldtProject(request):
    if request.method=="POST":
        ldt = request.POST['ldt']
        id = request.POST['id']
        ldtproject=Project.objects.get(ldt_id=id)
        #save xml ldt
        ldtproject.ldt=ldt
        #get new title
        dom = xml.dom.minidom.parseString(ldt.encode( "utf-8" ))
        con = xml.xpath.Context.Context(dom, 1, 1, None)
        result = xml.xpath.Evaluate("/iri/project",context=con)
        for pnode in result:
            title=pnode.getAttribute("title")
            break
        #set new title
        ldtproject.title=title
        #get new content list
        new_contents=[]
        result = xml.xpath.Evaluate("/iri/medias/media", context=con)
        for medianode in result:
            id = medianode.attributes['id'].value
            new_contents.append(id)
        # set new content list
        for c in ldtproject.contents.all():
            if not c.iri_id in new_contents:
                ldtproject.contents.remove(c)           
        ldtproject.save()
    else:
        ldt = ''
    return render_to_response('ldt/ldt_utils/save_done.html', {'ldt': ldt, 'id':id, 'title':title, 'contents': new_contents}, context_instance=RequestContext(request))
    
@login_required    
def publish(request, id):
    ldt = get_object_or_404(Project, ldt_id=id)
    ldt.state = 2 #published
    ldt.save()
    return HttpResponseRedirect(reverse("ldt.ldt_utils.views.list_ldt"))
    
@login_required    
def unpublish(request, id):
    ldt = get_object_or_404(Project, ldt_id=id)
    ldt.state = 1 #edition
    ldt.save()
    return HttpResponseRedirect(reverse("ldt.ldt_utils.views.list_ldt"))
    

def index(request, url):
    
    urlStr = settings.WEB_URL + reverse("ldt_init", args=['ldt',url])
    language_code = request.LANGUAGE_CODE[:2]
    
    return render_to_response('ldt/ldt_utils/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, 'weburl':settings.WEB_URL+settings.BASE_URL}, context_instance=RequestContext(request))


def ldt(request, url, startSegment = None):

    import Ft
    from Ft.Xml import MarkupWriter
    
    resp = HttpResponse(mimetype="text/xml; charset=utf-8")
    resp['Cache-Control'] = 'no-cache'

    contentList = Content.objects.filter(iri_id=url)

    ldtgen = LdtUtils()
    ldtgen.generateLdt(contentList, file=resp, title = contentList[0].title, startSegment=startSegment)

    return resp


def loading(request):
     return render_to_response('ldt/ldt_utils/loading.html', context_instance=RequestContext(request))


@login_required
def create_project(request, iri_id):

    content = get_object_or_404(Content, iri_id=iri_id)
    contents = [ content, ]
    if request.method == "POST" :
        form = AddProjectForm(request.POST)
        if form.is_valid():
            user=request.user
            project = Project.create_project(title=form.cleaned_data['title'], user=user, contents=contents)
            return HttpResponseRedirect(reverse('ldt.ldt_utils.views.indexProject', args=[project.ldt_id]))
    else:
        form = AddProjectForm()
    return render_to_response('ldt/ldt_utils/create_ldt.html', {'form':form, 'contents':contents, 'iri_id':iri_id, 'create_project_action':reverse("ldt.ldt_utils.views.create_project",args=[iri_id])}, context_instance=RequestContext(request))

@login_required
def copy_project(request, ldt_id):

    project = get_object_or_404(Project, ldt_id=ldt_id)
    if request.method == "POST" :
        form = CopyProjectForm(request.POST)
        if form.is_valid():
            user=request.user
            project = project.copy_project(title=request.POST['title'], user=user)
            return HttpResponseRedirect(reverse('ldt.ldt_utils.views.indexProject', args=[project.ldt_id]))
    else:
        form = CopyProjectForm
    return render_to_response('ldt/ldt_utils/copy_ldt.html', {'form':form, 'project':project}, context_instance=RequestContext(request))

