from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from ldt.ldt_utils.models import Content, Project
from ldt.ldt_utils.utils import LdtUtils, LdtSearch, clean_description
from ldt.security.utils import set_forbidden_stream
from ldt.ldt_utils.stat import update_stat_project
import base64
import django.core.urlresolvers
import lxml.etree
   
  
def search_index_get(request, field, query):
    
    language_code = request.LANGUAGE_CODE[:2]
    
    url = settings.WEB_URL + django.core.urlresolvers.reverse("ldt.ldt_utils.views.lignesdetemps.search_init", args=[field, query])
    return render_to_response('ldt/ldt_utils/init_ldt.html', {'LDT_MEDIA_PREFIX': settings.LDT_MEDIA_PREFIX, 'colorurl': settings.LDT_MEDIA_PREFIX + 'swf/ldt/pkg/color.xml', 'i18nurl': settings.LDT_MEDIA_PREFIX + 'swf/ldt/pkg/i18n', 'language': language_code, 'baseurl': settings.LDT_MEDIA_PREFIX + 'swf/ldt/', 'url': url}, context_instance=RequestContext(request))

def search_init(request, field, query):
    
    ldtgen = LdtUtils()
    
    doc = ldtgen.generate_init([field, query], 'ldt.ldt_utils.views.lignesdetemps.search_ldt', 'ldt.ldt_utils.views.lignesdetemps.search_segments')
    
    resp = HttpResponse(mimetype="text/xml;charset=utf-8")
    resp.write(lxml.etree.tostring(doc, pretty_print=True, encoding="utf-8")) 
    return resp

def search_ldt(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 = {}
        projIds = {}
        
        for result in searcher.query(field, queryStr):
            ids[result["iri_id"]] = ""
            projIds[result["project_id"]] = ""

        id_list = ids.keys()
        projId_list = projIds.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)        #@UndefinedVariable
        projectList = Project.safe_objects.filter(ldt_id__in=projId_list)    
          
    ldtgen = LdtUtils()
    #            generate_ldt(contentList, title=u"", author=u"IRI Web", web_url=u"", startSegment=None, projects=None):
    doc = ldtgen.generate_ldt(contentList, title=u"Recherche : " + queryStr, projects=projectList)
    doc = set_forbidden_stream(doc, request.user)   
    doc.write(resp, pretty_print=True)
    
    return resp


def search_segments(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")))

    iri = lxml.etree.Element('iri')
    doc = lxml.etree.ElementTree(iri)

    for resultMap in res:
        if iri_ids is None or resultMap['iri_id'] in iri_ids:
            seg = lxml.etree.SubElement(iri, 'seg')
            seg.set('idctt', resultMap['iri_id'])
            seg.set('idens', resultMap['ensemble_id'])
            seg.set('iddec', resultMap['decoupage_id'])
            seg.set('idseg', resultMap['element_id'])
            seg.set('idvue', "")
            seg.set('crit', "")
    
    #return doc  
    
    return HttpResponse(lxml.etree.tostring(doc, pretty_print=True), mimetype="text/xml;charset=utf-8") 



def index_segment(request, project_id, content_id, cutting_id, ensemble_id, segment_id):
    url_str = settings.WEB_URL + reverse("ldt.ldt_utils.views.lignesdetemps.init_segment", args=[project_id, content_id, ensemble_id, cutting_id, segment_id])
    post_url = ""
    language_code = request.LANGUAGE_CODE[:2]
    readonly = 'true'
    template_path = 'ldt/ldt_utils/init_ldt.html'
    
    return render_to_response(template_path, {'LDT_MEDIA_PREFIX': settings.LDT_MEDIA_PREFIX, 'colorurl': settings.LDT_MEDIA_PREFIX + 'swf/ldt/pkg/color.xml', 'i18nurl': settings.LDT_MEDIA_PREFIX + 'swf/ldt/pkg/i18n', 'language': language_code, 'baseurl': settings.LDT_MEDIA_PREFIX + 'swf/ldt/', 'url': url_str, 'posturl': post_url, 'id': id, 'readonly': readonly}, context_instance=RequestContext(request))
    
def init_segment(request, project_id, content_id, ensemble_id, cutting_id, segment_id):

    if project_id != u"_":
        get_object_or_404(Project.safe_objects, ldt_id=project_id)
    
    ldtgen = LdtUtils()
    doc = ldtgen.generate_init([project_id, content_id, ensemble_id, cutting_id, segment_id], 'ldt.ldt_utils.views.lignesdetemps.ldt_segment', 'ldt.ldt_utils.views.lignesdetemps.highlight_segment')
    
    return HttpResponse(lxml.etree.tostring(lxml.etree.ElementTree(doc), pretty_print=True), mimetype="text/xml;charset=utf-8")

def highlight_segment(request, project_id, content_id, ensemble_id, cutting_id, segment_id):
    if project_id != u"_":
        get_object_or_404(Project.safe_objects, ldt_id=project_id)
    
    iri = lxml.etree.Element('iri')
    doc = lxml.etree.ElementTree(iri)    

    seg = lxml.etree.SubElement(iri, 'seg')
    seg.set('idctt', content_id)
    seg.set('idens', ensemble_id)
    seg.set('iddec', cutting_id)
    seg.set('idseg', segment_id)
    seg.set('idvue', "")
    seg.set('crit', "")
  
    return HttpResponse(lxml.etree.tostring(doc, pretty_print=True), mimetype="text/xml;charset=utf-8") 


def ldt_segment(request, project_id, content_id, ensemble_id, cutting_id, segment_id): 

    resp = HttpResponse(mimetype="text/xml")
    resp['Cache-Control'] = 'no-cache, must-revalidate'
    resp['Pragma'] = 'no-cache'
    
    if project_id and project_id != "_" :
        project = Project.safe_objects.get(ldt_id=project_id) #@UndefinedVariable
        ldtdoc = lxml.etree.fromstring(project.ldt.encode("utf-8"))
        ldtdoc = set_forbidden_stream(ldtdoc, request.user)
        displays_node = ldtdoc.find("displays")
        if not displays_node:
            displays_node = lxml.etree.SubElement(ldtdoc, u"displays")        
        res = displays_node.xpath("display")
        if len(res) > 0:
            display_node = res[0]
        else:
            display_node = lxml.etree.SubElement(displays_node, u"display", attrib={u'id':u'0', u'title': u'generated', u'idsel':unicode(content_id), u'tc':u'0'})
        
        res = display_node.xpath("content[@id='%s']/decoupage[(@id='%s') and (@idens='%s')]" % (content_id, cutting_id, ensemble_id))
        if len(res) == 0:
            #create node
            res = display_node.xpath("content[@id='%s']" % (content_id))
            if len(res) == 0:
                content_node = lxml.etree.SubElement(display_node, u"content")
            else:
                content_node = res[0]
            lxml.etree.SubElement(content_node, u"decoupage", attrib={u'id':unicode(cutting_id), u'idens':unicode(ensemble_id)})
        active_segment_node = displays_node.find(u"activeSegment")
        if not active_segment_node:
            active_segment_node = lxml.etree.SubElement(displays_node, u"activeSegment")
        id_node = active_segment_node.find(u"id")
        if id_node:
            active_segment_node.remove(id_node)
        lxml.etree.SubElement(active_segment_node, u"id", attrib={u"idctt":unicode(content_id), u"idens": unicode(ensemble_id), "idcut":unicode(cutting_id), u"idseg":unicode(segment_id)})                     
        ldtdoc = set_forbidden_stream(ldtdoc, request.user)
        resp.write(lxml.etree.tostring(ldtdoc, xml_declaration=True, encoding='utf-8', pretty_print=True))
    else:
        # generate ldt from 
        ldtgen = LdtUtils()
        content_list = Content.safe_objects.filter(iri_id=content_id)
        if request.user and request.user.username:
            username = request.user.username
        else:
            username = "webuser"
        
        start_segment = {
            'idcontent': content_id,
            'idgroup' : ensemble_id,
            'idcutting' : cutting_id,
            'idsegment' : segment_id
        }        
        
        doc = ldtgen.generate_ldt(content_list, "segment : ", author=username, startSegment=start_segment)
        doc = set_forbidden_stream(doc, request.user)
        doc.write(resp, pretty_print=('DEBUG' in dir(settings) and settings.DEBUG))
        
    return resp
        
   
@login_required    
def index_project(request, id, full=False): 

    urlStr = settings.WEB_URL + reverse("ldt.ldt_utils.views.lignesdetemps.init", args=['ldt_project', id])
    posturl = settings.WEB_URL + reverse("ldt.ldt_utils.views.lignesdetemps.save_ldt_project")
    language_code = request.LANGUAGE_CODE[:2]
    
    try:
        ldt = Project.safe_objects.get(ldt_id=id)
    except Project.DoesNotExist:
        return HttpResponseRedirect(reverse("ldt.ldt_utils.views.workspace.home"))
    
    if ldt.state == 2 or not request.user.has_perm('change_project', ldt): #published
        readonly = 'true'
    else:
        readonly = 'false'
       
    if full:
        template_path = 'ldt/ldt_utils/init_ldt_full.html'
    else:
        template_path = 'ldt/ldt_utils/init_ldt.html'
  
    return render_to_response(template_path, {'LDT_MEDIA_PREFIX': settings.LDT_MEDIA_PREFIX, 'colorurl': settings.LDT_MEDIA_PREFIX + 'swf/ldt/pkg/color.xml', 'i18nurl': settings.LDT_MEDIA_PREFIX + 'swf/ldt/pkg/i18n', 'language': language_code, 'baseurl': settings.LDT_MEDIA_PREFIX + 'swf/ldt/', 'url': urlStr, 'posturl': posturl, 'id': id, 'readonly': readonly}, context_instance=RequestContext(request))
    
    
def init(request, method, url):
    ldtgen = LdtUtils()

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

    library = doc.xpath('/iri/files/library')[0]
    for c in Content.safe_objects.all():
        elem = lxml.etree.SubElement(library, 'file')
        elem.set('src', c.iri_url())
        if c.videopath :
            elem.set('video', c.videopath)
        else :
            elem.set('video', '')
        elem.set('title', c.title)
        elem.set('author', '')
        elem.set('category', '')
        elem.set('pict', '')
        elem.set('img', '')

    resp = HttpResponse(mimetype="text/xml")
    resp['Cache-Control'] = 'no-cache, must-revalidate'
    resp['Pragma'] = 'no-cache'

    resp.write(lxml.etree.tostring(doc, pretty_print=True, xml_declaration=True, encoding="utf-8")) 
    return resp
       
def ldt_project(request, id): 
    resp = HttpResponse(mimetype="text/xml")
    resp['Cache-Control'] = 'no-cache, must-revalidate'
    resp['Pragma'] = 'no-cache'
    
    project = Project.safe_objects.get(ldt_id=id) #@UndefinedVariable
    
    doc = lxml.etree.fromstring(project.ldt)
    doc = set_forbidden_stream(doc, request.user)
    resp.write(lxml.etree.tostring(doc, pretty_print=True, xml_declaration=True, encoding="utf-8")) 

    return resp



def save_ldt_project(request):
    if request.method == "POST":
        ldt = request.POST['ldt']
        id = request.POST['id']
        ldtproject = Project.safe_objects.select_related().get(ldt_id=id) #@UndefinedVariable

        #save xml ldt
        ldtproject.ldt = ldt

        doc = lxml.etree.fromstring(ldtproject.ldt.encode("utf-8"))
        result = doc.xpath("/iri/project")
        
        #set new title
        ldtproject.title = result[0].get("title")
        
        #get new content list
        new_contents = []
        result = doc.xpath("/iri/medias/media")
        for medianode in result:
            id = medianode.get("id")
            new_contents.append(id)
    
        check_icon_project = False
        
        #find contents to remove
        for c in ldtproject.contents.all():
            if not c.iri_id in new_contents:
                ldtproject.contents.remove(c)
                if ldtproject.image == c.image:
                    check_icon_project = True
        
        #add new contents
        contents_id = [c.iri_id for c in ldtproject.contents.all()]
        
        for c in new_contents:
            if c not in contents_id:
                content = Content.objects.get(iri_id=c)
                ldtproject.contents.add(content)
         
        update_stat_project(ldtproject)
        
        #remove html tags added by flash
        description = ldtproject.get_description(doc)
        new_desc = clean_description(description)
            
        if new_desc:        
            desc_node = doc.xpath('/iri/project')[0]
            desc_node.set('abstract', new_desc)
            ldtproject.ldt = lxml.etree.tostring(doc, pretty_print=True)
            
        ldtproject.description = new_desc if new_desc else description
    
        #set a new icon for this project
        if check_icon_project:
            ldtproject.set_icon()
    
        ldtproject.save()
            
    else:
        ldt = ''
        new_contents = []
    
    return render_to_response('ldt/ldt_utils/save_done.html', {'ldt': ldt, 'id':id, 'title':ldtproject.title, 'contents': new_contents}, context_instance=RequestContext(request))
    

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


def ldt(request, url, startSegment=None): 
    
    resp = HttpResponse(mimetype="text/xml; charset=utf-8")
    resp['Cache-Control'] = 'no-cache'

    contentList = Content.safe_objects.filter(iri_id=url) #@UndefinedVariable

    ldtgen = LdtUtils()
    doc = ldtgen.generate_ldt(contentList, title=contentList[0].title, startSegment=startSegment)
    doc = set_forbidden_stream(doc, request.user)
    doc.write(resp, pretty_print=True)

    return resp


