from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.core.urlresolvers import reverse#, resolve
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.http import HttpResponseForbidden, HttpResponse
from ldt.indexation import get_results_with_context, highlight_documents
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils.html import escape
from django.utils.translation import ugettext as _
from ldt.ldt_utils.forms import SearchForm
from ldt.ldt_utils.models import Content, Project, Segment
from ldt.ldt_utils.utils import boolean_convert
from ldt.ldt_utils.projectserializer import ProjectJsonSerializer
from ldt.ldt_utils.views.content import get_contents_page, get_content_tags
from ldt.ldt_utils.views.project import get_projects_page, get_published_projects_page
from ldt.security.utils import add_change_attr, get_userlist
from ldt.templatetags import absurl
from operator import itemgetter
from itertools import groupby
import base64
import django.core.urlresolvers
import ldt.auth as ldt_auth
from django.utils.safestring import mark_safe
from django.contrib.sites.models import Site
from django.template import Context, Template
import logging



@login_required
def home(request):
    
    num_page = 0
    # Prepare contents pagination
    content_nb, nb_ct_pages, content_list = get_contents_page(num_page, request.user)
    # get list of projects owned by the current user
    project_nb, nb_pj_pages, project_list = get_projects_page(num_page, request.user)
    # Get the all tags list
    tag_cloud = get_content_tags()

    is_gecko = ((request.META['HTTP_USER_AGENT'].lower().find("firefox")) > -1);
    
    # render list
    return render_to_response("ldt/ldt_utils/workspace.html",
                              {'contents': content_list, 'nb_ct_pages': nb_ct_pages, 'content_nb': content_nb, 'current_content_page':float(num_page),
                               'projects': project_list, 'nb_pj_pages': nb_pj_pages, 'project_nb': project_nb, 'current_project_page':float(num_page),
                               'tag_cloud': tag_cloud, 'is_gecko': is_gecko, #'project_api_url':"match.url_name",
                               #'project_api_view':match.url_name,'project_api_args':"project_api_args",'project_api_kwargs':"project_api_kwargs"
                               },
                              context_instance=RequestContext(request))

    

@login_required
def groups(request): 

    # get list of all published projects
    group_list = request.user.groups.exclude(name=settings.PUBLIC_GROUP_NAME)
    
    group_list = sorted(group_list.all(), key=lambda group: group.name.lower())    
    group_list = add_change_attr(request.user, group_list)

    can_add_group = request.user.has_perm('auth.add_group')
    is_gecko = ((request.META['HTTP_USER_AGENT'].lower().find("firefox")) > -1);
    # render list
    return render_to_response("ldt/ldt_utils/groups.html",
                              {'groups': group_list,
                               'is_gecko': is_gecko,
                               'can_add_group': can_add_group},
                              context_instance=RequestContext(request))


@login_required
def published_project(request): 

    # get list of all published projects
    #project_list = Project.safe_objects.filter(state=2).exclude(title__startswith='front') #@UndefinedVariable
    num_page = 0
    project_nb, nb_pj_pages, project_list = get_published_projects_page(num_page)
    # Search form
    form = SearchForm()

    is_gecko = ((request.META['HTTP_USER_AGENT'].lower().find("firefox")) > -1);
    
    # render list
    return render_to_response("ldt/ldt_utils/published_projects.html",
                              {'projects': project_list, 'nb_pj_pages': nb_pj_pages, 'project_nb': project_nb, 'current_project_page':float(num_page), 
                               'form': form, 'is_gecko': is_gecko},
                              context_instance=RequestContext(request))


def popup_embed(request):

    json_url = request.GET.get("json_url")
    player_id = request.GET.get("player_id")
    ldt_id = request.GET.get("ldt_id")
    rend_dict = get_datas_for_embed(request, json_url, player_id, ldt_id)
    
    embed_rendered = dict((typestr,
                           (lambda s:escape(render_to_string("ldt/ldt_utils/partial/embed_%s.html" % (s), rend_dict, context_instance=RequestContext(request))))(typestr))
                           for typestr in ('seo_body', 'seo_meta', 'links'))

    rend_dict['embed_rendered'] = embed_rendered
    return render_to_response("ldt/ldt_utils/embed_popup.html", rend_dict, context_instance=RequestContext(request))


def iframe_embed(request):

    project_id = request.GET.get("project_id")
    if not project_id:
        content_id = request.GET.get("content_id")
        try:
            content = Content.safe_objects.get(iri_id=content_id)
        except:
            return HttpResponseForbidden(_("The content does not exists or you are not allowed to access this content"))
        project = content.get_or_create_front_project()
        project_id = project.ldt_id
    if not project_id :
        return HttpResponseForbidden(_("Parameters project_id or content_id must be given in the url"))
        
    json_url = reverse("projectjson_id", args=[project_id])
    player_id = "player_project_" + project_id
    ldt_id = project_id
    rend_dict = get_datas_for_embed(request, json_url, player_id, ldt_id)
    
    # Manage iframe options
    rend_dict["player_height"]=request.GET.get("player_height")
    rend_dict["player_width"]=request.GET.get("player_width")
    if request.GET.has_key("polemic"):
        rend_dict["polemic"] = request.GET.get("polemic")
        rend_dict["polemic_defaultColor"] = request.GET.get("polemic_defaultColor")
        rend_dict["polemic_foundColor"] = request.GET.get("polemic_foundColor")
        rend_dict["polemic_okColor"] = request.GET.get("polemic_okColor")
        rend_dict["polemic_koColor"] = request.GET.get("polemic_koColor")
        rend_dict["polemic_refColor"] = request.GET.get("polemic_refColor")
        rend_dict["polemic_qColor"] = request.GET.get("polemic_qColor")

    if request.GET.has_key("show_mic_record"):
        rend_dict["show_mic_record"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("show_mic_record").lower())
    if request.GET.has_key("annotations_list"):
        rend_dict["annotations_list"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("annotations_list").lower())
        rend_dict["player_width"] = 550
    if request.GET.has_key("createannotation"):
        rend_dict["createannotation"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("createannotation").lower())
    if request.GET.has_key("tag_titles"):
       rend_dict["tag_titles"] = request.GET.get("tag_titles") 
    if request.GET.has_key("sparkline"):
        rend_dict["sparkline"] = request.GET.get("sparkline")
        rend_dict["sparkline_lineColor"] = request.GET.get("sparkline_lineColor")
        rend_dict["sparkline_fillColor"] = request.GET.get("sparkline_fillColor")
    if request.GET.has_key("slideshare"):
        rend_dict["slideshare"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("slideshare").lower())
    if request.GET.has_key("social"):
        rend_dict["social"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("social").lower())     
        if request.GET.has_key("show_url"):
            rend_dict["show_url"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("show_url").lower())     
        if request.GET.has_key("show_twitter"):
            rend_dict["show_twitter"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("show_twitter").lower())     
        if request.GET.has_key("show_fb"):
            rend_dict["show_fb"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("show_fb").lower())     
        if request.GET.has_key("show_gplus"):
            rend_dict["show_gplus"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("show_gplus").lower())     
        if request.GET.has_key("show_mail"):
            rend_dict["show_mail"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("show_mail").lower())     
    if request.GET.has_key("annotation"):
        rend_dict["annotation"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("annotation").lower())
    if request.GET.has_key("tweet"):
        rend_dict["tweet"] ={'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("tweet").lower())
    if request.GET.has_key("segments"):
        rend_dict["segments"] = request.GET.get("segments")
    if request.GET.has_key("tagcloud"):
        rend_dict["tagcloud"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("tagcloud").lower())
    return render_to_response("ldt/ldt_utils/embed_iframe.html", rend_dict, context_instance=RequestContext(request))


def get_datas_for_embed(request, json_url, player_id, ldt_id):
    
    project = Project.safe_objects.get(ldt_id=ldt_id); #@UndefinedVariable
    project_contents = project.contents.all()
    content=project_contents[0]
    iframe_url = mark_safe(settings.WEB_URL+settings.BASE_URL+"ldtplatform/ldt/embediframe/?content_id="+content.iri_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 stream_mode == 'radio':
        player_height = 1
        
    if not ldt_auth.check_access(request.user, project):
        return HttpResponseForbidden(_("You can not access this project"))
    WEB_URL=settings.WEB_URL
    LANGUAGE_CODE=settings.LANGUAGE_CODE
    ps = ProjectJsonSerializer(project, from_contents=True, from_display=True)
    annotations = ps.get_annotations(first_cutting=True)
    rend_dict = {'json_url':json_url, 'player_id':player_id, 'annotations':annotations, 'ldt_id': ldt_id, 'stream_mode': stream_mode, 
                'external_url': external_url,
                 'polemic':False, 'show_mic_record':False, 'annotations_list':False, 'iframe_url':iframe_url, 'WEB_URL':WEB_URL,
                'LANGUAGE_CODE':LANGUAGE_CODE}
    return rend_dict



def share_filter(request, filter, use_groups=False):
    use_groups = boolean_convert(use_groups)
    if not filter or len(filter) == 0:
        raise AttributeError("filter should be a string")
    
    filter = filter[1:]    
    resp = get_userlist(request.user, filter=filter)
            
    if use_groups:
        groups = Group.objects.filter(name__icontains=filter).exclude(name=settings.PUBLIC_GROUP_NAME)[0:20]

        for g in groups:
            resp.append({'name': g.name, 'id': g.id, 'type': 'group'})
    
    resp = sorted(resp, key=lambda elem: elem['name'].lower())
    
    return render_to_response("ldt/ldt_utils/partial/sharewith.html", {'elem_list' : resp}, context_instance=RequestContext(request))



def search_form(request): 
    form = SearchForm()
    return render_to_response('ldt/ldt_utils/search_form.html', {'form': form} , context_instance=RequestContext(request))

@login_required
def search_index(request):
    language_code = request.LANGUAGE_CODE[:2]
    nb = 0
    results = []
    search = ''
    field = 'all'
    context_color = Context({}) 
    template_colorurl_string = """
      {% load absstatic %}
      {% absstatic "ldt/swf/ldt/pkg/color.xml" %}
   """
    t_colorurl = Template(template_colorurl_string)
    t_colorurl_render = t_colorurl.render(context_color)
    colorurl=t_colorurl_render.strip()
    context_i18nurl = Context({}) 
    template_i18nurl_string = """
      {% load absstatic %}
      {% absstatic "ldt/swf/ldt/pkg/i18n" %}
   """
    t_i18nurl = Template(template_i18nurl_string)
    t_i18nurl_render = t_i18nurl.render(context_i18nurl)
    i18nurl=t_i18nurl_render.strip()
    context_baseurl = Context({}) 
    template_baseurl_string = """
      {% load absstatic %}
      {% absstatic "ldt/swf/ldt/" %}
   """
    t_baseurl = Template(template_baseurl_string)
    t_baseurl_render = t_baseurl.render(context_i18nurl)
    baseurl=t_baseurl_render.strip()
        
    sform = SearchForm(request.GET)
    if sform.is_valid():
        search = sform.cleaned_data["search"]
        queryStr = base64.urlsafe_b64encode(search.encode('utf8'))
        field = sform.cleaned_data["field"]
        page = sform.cleaned_data["page"] or 1
        ldt_pres = sform.cleaned_data["ldt_pres"]
        if ldt_pres:
            #the following code will use the absurl templatetag to have the url and stop using WEB_URL+reverse
            context_url = Context({}) 
            template_url_string = """
              {% load absurl %}
              {% absurl  ldt.ldt_utils.views.lignesdetemps.search_init field='"""+field+"""' query='"""+queryStr+"""' %}
           """
            t_url = Template(template_url_string)
            t_render= t_url.render(context_url)
            url=t_render.strip()
            #url = settings.WEB_URL + django.core.urlresolvers.reverse("ldt.ldt_utils.views.lignesdetemps.search_init", args=[field, queryStr])
            return render_to_response('ldt/ldt_utils/init_ldt_full.html', {'colorurl': colorurl, 'i18nurl': i18nurl , 'language': language_code, 'baseurl': baseurl, 'url': url}, context_instance=RequestContext(request))
        else:                                        
            results, nb = get_search_results(request, search, field, page)            
            
    return render_to_response('ldt/ldt_utils/search_results.html', {'results': results, 'nb_results' : nb, 'search' : search, 'field': field, 'colorurl': colorurl, 'i18nurl': i18nurl , 'language': language_code, 'baseurl': baseurl}, context_instance=RequestContext(request))
        
 
def get_search_results(request, search, field, page, content_list=None):
    # We parse the author if necessary. For author search to work in every case, we have to transform the query author:cheese shop into author:"CHEESE SHOP"
    if u'author:' in search.lower() :
        sub = search[7:]
        sub = sub.upper()
        if sub[0] != u'"':
            sub = u'"' + sub
        if sub[-1] != u'"':
            sub = sub + u'"'
        search = u'author:' + sub
    results = get_results_with_context(field, search, content_list)
            
    all_segments = Segment.objects.filter(element_id__in=[e['element_id'] for e in results])
    all_projects = Project.objects.filter(ldt_id__in=[e['project_id'] for e in results], state=2)
    all_contents = Content.objects.filter(iri_id__in=[e['iri_id'] for e in results])
    viewable_projects_id = [p.ldt_id for p in all_projects]
           
    complete_results = []           
    results.sort(key=lambda k: k['iri_id'])
           
    for iri_id, item in groupby(results, itemgetter('iri_id')):
        content = filter(lambda e: e.iri_id == iri_id, all_contents)[0]
        if content.description is None:
            content.description = ''
                    
        all_related_segments = list(item)
                
        valid_segments = []
        for s in all_related_segments:
            array_of_segs = [seg for seg in all_segments if seg.element_id == s['element_id'] and seg.project_id == s['project_id'] and seg.iri_id == s['iri_id'] and seg.cutting_id == s['cutting_id'] and seg.ensemble_id == s['ensemble_id'] ]
            if len(array_of_segs)>0:
                segment = array_of_segs[0]
                    
                segment.score = s['score']
                segment.indexation_id = s['indexation_id']
                segment.context = s['context']
                segment.context_tags = s['tags']
                segment.highlighted = s['highlighted']
                                        
                if not s['project_id']:
                    segment.project_id = '_'
                    valid_segments.append(segment)
                elif s['project_id'] in viewable_projects_id:
                    valid_segments.append(segment)
            
        # If all segments found belong to unpublished projects or projects
        # the current user is not allowed to see
        if not valid_segments:
            continue
            
        score = sum([seg.score for seg in valid_segments])
        complete_results.append({
                                 'list': valid_segments,
                                 'score': score,
                                 'content': content,                                         
                                 })                
      
    complete_results.sort(key=lambda k: k['score'])
    
    paginator = Paginator (complete_results, settings.LDT_RESULTS_PER_PAGE)
    
    try:
        results = paginator.page(page)
    except (EmptyPage, InvalidPage):
        results = paginator.page(paginator.num_pages)
            
    results.object_list = highlight_documents(results.object_list, search, field)
    
    return results, len(complete_results)
   

def loading(request): 
    return render_to_response('ldt/ldt_utils/loading.html', context_instance=RequestContext(request))
   

