import base64
import logging

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


logger = logging.getLogger(__name__)

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(Segment, 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()
        
        logger.debug("search_generate_ldt : getting content list")    
        contentList = Content.objects.filter(iri_id__in=id_list).select_related("front_project", "media_obj")        #@UndefinedVariable
        logger.debug("search_generate_ldt : getting project list")
        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):
    logger.debug("search_generate_ldt : generate ldt")
    doc = ldtgen.generate_ldt(contentList, title=u"Recherche : " + queryStr, projects=projectList, types_id_list=typesId_list)
    
    logger.debug("search_generate_ldt : set forbidden streams")
    doc = set_forbidden_stream(doc, request.user)
    
    logger.debug("search_generate_ldt : done")
    return doc, results