import base64
from itertools import groupby
from operator import itemgetter

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse #, resolve
from django.db import transaction
from django.http import (HttpResponseForbidden, HttpResponseNotFound, 
    HttpResponseRedirect)
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.safestring import mark_safe
from django.utils.translation import ugettext as _
import lxml.etree

import ldt.auth as ldt_auth
from ldt.indexation import get_results_with_context, highlight_documents
from ldt.ldt_utils import contentindexer
from ldt.ldt_utils.forms import SearchForm
from ldt.ldt_utils.models import Content, Project, Segment
from ldt.ldt_utils.projectserializer import ProjectJsonSerializer
from ldt.ldt_utils.utils import boolean_convert
from ldt.ldt_utils.views.content import get_contents_page
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.utils.url import static, absurl
from ldt.utils.web_url_management import get_web_url


@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)

    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),
                               'is_gecko': is_gecko
                               },
                              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):

    content_id = request.GET.get("content_id")
    project_id = request.GET.get("project_id")
    if not project_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", kwargs={'id':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)
    
    # Test if concatenated projects has been asked
    concatenate_projects = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("concatenate_projects", "").lower())
    if concatenate_projects:
        json_url = reverse("api_content_all_projects", kwargs={'api_name': '1.0', 'resource_name': 'contents', 'iri_id': content_id})
        # add filter
        group_id = request.GET.get("group")
        if group_id is not None :
            json_url += "?group=" + group_id
        rend_dict["json_url"] = json_url
        
    
    # Manage iframe options
    if request.GET.has_key("player_height"):
        rend_dict["player_height"]=request.GET.get("player_height")
    else:
        rend_dict["player_height"]=300
    if request.GET.has_key("player_width"):
        rend_dict["player_width"]=request.GET.get("player_width")
    else:
        rend_dict["player_width"]=550
    if request.GET.has_key("polemic"):
        rend_dict["polemic"] = request.GET.get("polemic")
        if request.GET.has_key("polemic_defaultColor"):
            rend_dict["polemic_defaultColor"] = request.GET.get("polemic_defaultColor")
        else:
            rend_dict["polemic_defaultColor"]="585858"
        if request.GET.has_key("polemic_foundColor"):
            rend_dict["polemic_foundColor"] = request.GET.get("polemic_foundColor")
        else:
            rend_dict["polemic_foundColor"]="fc00ff"
        if request.GET.has_key("polemic_okColor"):
            rend_dict["polemic_okColor"] = request.GET.get("polemic_okColor")
        else:
            rend_dict["polemic_okColor"] = "1d973d"
        if request.GET.has_key("polemic_koColor"):
            rend_dict["polemic_koColor"] = request.GET.get("polemic_koColor")
        else:
            rend_dict["polemic_koColor"]="ce0a15"
        if request.GET.has_key("polemic_refColor"):
            rend_dict["polemic_refColor"] = request.GET.get("polemic_refColor")
        else:
            rend_dict["polemic_refColor"] = "c5a62d"
        if request.GET.has_key("polemic_qColor"):
            rend_dict["polemic_qColor"] = request.GET.get("polemic_qColor")
        else:
            rend_dict["polemic_qColor"] = "036aae"
        if request.GET.has_key("polemics_list"):
            try:
                # Very rough : has to be something like 
                # [{"name":"OK","keywords":["%2B%2B"],"color":"%23DDDDDD"},{"name":"KO","keywords":["--"],"color":"%23AAAAAA"},{"name":"REF","keywords":["==","http://"],"color":"%23777777"},{"name":"Q","keywords":["?"],"color":"%23333333"}]
                pd = request.GET.get("polemics_list")
            except:
                pd = False
            rend_dict["polemics_list"] = pd
        else:
            rend_dict["polemics_list"] = False
        if request.GET.has_key("polemic__max_elements"):
            try:
                pme = int(request.GET.get("polemic__max_elements"))
            except:
                pme = 20
            rend_dict["polemic__max_elements"] = pme
        else:
            rend_dict["polemic__max_elements"] = 20
            
    if request.GET.has_key("autostart"):
        rend_dict["autostart"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("autostart").lower())
    else : 
        rend_dict["autostart"] = True
    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("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 rend_dict["show_mic_record"]:
            rend_dict["createannotation"]=True
    rend_dict["createannotation_polemics"] = True
    if request.GET.has_key("createannotation_polemics"):
        rend_dict["createannotation_polemics"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("createannotation_polemics").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("tag_titles"):
        rend_dict["tag_titles"] = request.GET.get("tag_titles")
    if request.GET.has_key("sparkline"):
        rend_dict["sparkline"] = request.GET.get("sparkline")
        if request.GET.has_key("sparkline_lineColor"):
            rend_dict["sparkline_lineColor"] = request.GET.get("sparkline_lineColor")
        else:
            rend_dict["sparkline_lineColor"] = "7492b4"
        if request.GET.has_key("sparkline_fillColor"):
            rend_dict["sparkline_fillColor"] = request.GET.get("sparkline_fillColor")
        else:
            rend_dict["sparkline_fillColor"] = "aeaeb8"
    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())
        else:
            rend_dict["show_url"] = True    
        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())     
        else:
            rend_dict["show_twitter"] = True
        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())     
        else:
            rend_dict["show_fb"] = True
        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())     
        else:
            rend_dict["show_gplus"] = True
        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())     
        else:
            rend_dict["show_mail"] = True
    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"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("segments").lower())
    else:
        rend_dict["segments"] = True
    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.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(WEB_URL+settings.BASE_URL+"ldtplatform/ldt/embediframe/?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,
                 '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):  # @ReservedAssignment
    use_groups = boolean_convert(use_groups)
    if not filter or len(filter) == 0:
        raise AttributeError("filter should be a string")
    
    filter = filter[1:]    # @ReservedAssignment
    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
    nb_segment=0
    results = []
    search = ''
    field = 'all'
    colorurl = static("ldt/swf/ldt/pkg/color.xml")
    i18nurl = static("ldt/swf/ldt/pkg/i18n")
    baseurl = static("ldt/swf/ldt/")
    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:
            url = absurl(request, "ldt.ldt_utils.views.lignesdetemps.search_init", kwargs={'field':field, 'query':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, nb_segment = get_search_results(request, search, field, page)            
            
    return render_to_response('ldt/ldt_utils/search_results.html', {'results': results, 'nb_results' : nb, 'nb_segment' : nb_segment, '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(Segment, 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]).select_related('stat_annotation')
    viewable_projects_id = [p.ldt_id for p in all_projects]
    nb_segment=0       
    complete_results = []           
    results.sort(key=lambda k: k['iri_id'])
           
    for iri_id, item in groupby(results, itemgetter('iri_id')):
        content=None
        content_filter = filter(lambda e: e.iri_id == iri_id, all_contents)
        if len(content_filter)>0:
            content = content_filter[0]
            if content.description is None:
                content.description = ''
        if content is None:
            continue
        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)
                    nb_segment+=1
                elif s['project_id'] in viewable_projects_id:
                    valid_segments.append(segment)
                    nb_segment+=1
            
        # 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), nb_segment
   

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

@transaction.commit_on_success
def delete_segment(request, project_id, content_id, ensemble_id, cutting_id, segment_id):
    if project_id and project_id != "_" :
        project = Project.safe_objects.get(ldt_id=project_id) #@UndefinedVariable
        if project:
            ldtdoc = lxml.etree.fromstring(project.ldt_encoded)
            xstr = "/iri/annotations/content[@id='%s']/ensemble[@id='%s']/decoupage[@id='%s']/elements/element[@id='%s']" % (content_id, ensemble_id, cutting_id, segment_id)
            element = None
            try:
                element = ldtdoc.xpath(xstr)
            except:
                return HttpResponseNotFound(_("Annotation not found in the xml"))
            if element and len(element)>0:
                # element[0] is the annotation to remove
                el = element[0]
                el.getparent().remove(el)
                project.ldt = lxml.etree.tostring(ldtdoc)
                project.save(must_reindex=False)
                contentindexer.delete_segment(project, project_id, content_id, ensemble_id, cutting_id, segment_id)                
                
                return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
            else:
                return HttpResponseNotFound(_("Annotation not found"))
        else:
            return HttpResponseNotFound(_("Project not found"))
    else:
        return HttpResponseNotFound(_("Project not found"))

