import lucene
from blinkster.ldt import STORE
from blinkster.ldt import ANALYZER
import uuid
import django.core.urlresolvers
import blinkster.settings
from Ft.Xml import MarkupWriter
import xml.dom
import xml.dom.minidom
import xml.dom.ext
import xml.xpath
import os
import os.path



class LdtSearch(object):

	def query(self, field, query):
		indexSearcher = lucene.IndexSearcher(STORE)
		#queryParser = lucene.MultiFieldQueryParser(["tags","title","abstract"], ANALYZER)
		queryParser = lucene.QueryParser(field, lucene.FrenchAnalyzer())
		queryParser.setDefaultOperator(lucene.QueryParser.Operator.AND)
		queryObj = queryParser.parse(query)
		hits = indexSearcher.search(queryObj)
		
		res = []
		for hit in hits:
			doc = lucene.Hit.cast_(hit).getDocument()
			res.append({"iri_id":doc.get("iri_id"),"ensemble_id":doc.get("ensemble_id"),"decoupage_id":doc.get("decoupage_id"), "element_id":doc.get("element_id")})
		return res

	
	def queryAll(self, query):		
		return self.query("all", query)
	
class LdtUtils(object):
    
    def generateLdt(self, contentList, file, title = u"", author=u"IRI Web", web_url=u"", media_url=""):
        writer = MarkupWriter(file, indent = u"yes")
        writer.startDocument()
        writer.startElement(u"iri")
        writer.simpleElement(u"project", attributes={u"id":unicode(str(uuid.uuid1())), u"title":unicode(title) , u"user":author, u"abstract":u""})
        writer.startElement(u"medias")
        for content in contentList:
            writer.simpleElement(u"media", attributes={u"id":content.iri_id,u"src":content.iri_url(web_url),u"video":unicode(media_url)+unicode(blinkster.settings.STREAM_URL),u"pict":u"",u"extra":u""})
        writer.endElement(u"medias")
        writer.simpleElement(u"annotations")
        writer.startElement(u"displays")
        if len(contentList) > 0:
            writer.startElement(u"display", attributes={u"id":u"0",u"title":u"generated",u"idsel":contentList[0].iri_id,u"tc":u"0"})
            for content in contentList:
                writer.startElement(u"content", attributes={u"id":content.iri_id})
                doc = xml.dom.minidom.parse(content.iri_file_path())
                con = xml.xpath.Context.Context(doc, 1, 1, None)
                res = xml.xpath.Evaluate("/iri/body/ensembles/ensemble/decoupage", context=con)
                for decoupagenode in res:
                    decoupage_id = decoupagenode.getAttribute(u"id")
                    ensemble_id = decoupagenode.parentNode.getAttribute(u"id")
                    writer.simpleElement(u"decoupage", attributes={u"id":decoupage_id,u"idens":ensemble_id})
                writer.endElement(u"content")
            writer.endElement(u"display")
        writer.endElement(u"displays")
        writer.simpleElement(u"edits")
        writer.endElement(u"iri")

    def generateInit(self, url, method, search=None):
        
        import xml.dom
        import xml.dom.ext
    
        impl = xml.dom.getDOMImplementation()
        doc = impl.createDocument(xml.dom.EMPTY_NAMESPACE, 'iri', None)
    
        elementFiles = doc.createElement('files')
        doc.documentElement.appendChild(elementFiles)
    
        elementInit = doc.createElement('init')
        elementFiles.appendChild(elementInit)
    
        elementfile = doc.createElement('file')
            
        elementfile.setAttribute('src',blinkster.settings.WEB_URL + django.core.urlresolvers.reverse(method, args=url))
        elementfile.setAttribute('display', '1')
        if(search):
            elementfile.setAttribute("segsel",blinkster.settings.WEB_URL + django.core.urlresolvers.reverse(search, args=url))
    
    
        #/*chemin video : tant que le serveur de media n'est pas up, */
        elementfile.setAttribute('video', blinkster.settings.STREAM_URL)
        elementfile.setAttribute('pict', "")
        elementfile.setAttribute('extra', "")
    
        elementInit.appendChild(elementfile);
    
        elementRecent = doc.createElement('recent');
        elementFiles.appendChild(elementRecent);
    
    
        elementLibrary = doc.createElement('library');
        elementFiles.appendChild(elementLibrary);
    
        username = ''
        id = ''
        elementUser = doc.createElement('user')
        elementUser.setAttribute('name', username)
        elementUser.setAttribute('id', id)
        doc.documentElement.appendChild(elementUser)
        
        return doc
                
