from ldt.indexation import SimpleSearch
from ldt.ldt_utils.models import Content, Project
from ldt.ldt_utils.utils import LdtUtils
from ldt.security.utils import set_forbidden_stream
import base64


def search_generate_ldt(request, field, query, query_encoded=True): 
    
    contentList = []
    queryStr = ""

    if query and len(query) > 0: 
        if query_encoded:
            queryStr = base64.urlsafe_b64decode(query.encode("ascii")).decode("utf8")
        else:
            queryStr = query
        searcher = SimpleSearch()
        ids = {}
        projIds = {}
        typesIds = {}
        results = searcher.query(field, queryStr)
        for result in results:
            ids[result["iri_id"]] = ""
            projIds[result["project_id"]] = ""
            typesIds[result["cutting_id"]] = ""

        id_list = ids.keys()
        projId_list = projIds.keys()
        typesId_list = typesIds.keys()
            
        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, types_id_list=typesId_list)
    doc = set_forbidden_stream(doc, request.user)
    
    return doc, results