from django.conf import settings
from django.utils.safestring import mark_safe

import ldt.auth as ldt_auth
from ldt.ldt_utils.projectserializer import ProjectJsonSerializer
from ldt.utils.web_url_management import get_web_url


from ldt.ldt_utils.models import Project
from urlparse import urljoin



def get_datas_for_embed(request, json_url, player_id, ldt_id, iframe_base_url):
        project = Project.safe_objects.prefetch_related("contents", "owner").get(ldt_id=ldt_id) #@UndefinedVariable
        project_contents = project.contents.all()
        content = project_contents[0]
        WEB_URL = get_web_url(request)
        iframe_url = mark_safe(urljoin(WEB_URL,str(iframe_base_url)+"?content_id="+content.iri_id+"&project_id="+ldt_id))
        external_url = None
        if content.src is not None:
            for external_src in settings.EXTERNAL_STREAM_SRC:
                if  external_src in content.src:
                    external_url = content.src
                    break
        
        stream_mode = project.stream_mode
        if stream_mode != "video":
            stream_mode = 'radio'
            
        if not ldt_auth.check_access(request.user, project):
            # If the project is unpublished AND if the user is the owner, we display few datas
            #TODO : enhance rend_dict and display in this case
            if project.state==1 and project.owner==request.user:
                pass
            else:
                #return HttpResponseForbidden(_("You can not access this project"))
                return {'ldt_id': ldt_id}
        LANGUAGE_CODE = settings.LANGUAGE_CODE
        ps = ProjectJsonSerializer(project, from_contents=True, from_display=True)
        annotations = ps.get_annotations(first_cutting=True)
        rend_dict = {'project':project, 'contents':project_contents, 'json_url':json_url, 'player_id':player_id, 'annotations':annotations, 'ldt_id': ldt_id, 'stream_mode': stream_mode,  
                    'external_url': external_url, 'content_id': content.iri_id,
                     'polemic':False, 'show_mic_record':False, 'annotations_list':False, 'iframe_url':iframe_url, 'WEB_URL':WEB_URL,
                    'LANGUAGE_CODE':LANGUAGE_CODE}
        return rend_dict