from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group, User
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseServerError
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.utils import simplejson
from guardian.shortcuts import get_objects_for_group
from ldt.ldt_utils.models import Content, Project, Segment
from ldt.ldt_utils.views.workspace import search_index as ws_search_index, search_listing as ws_search_listing
from ldt.security.utils import add_change_attr
from tagging.models import Tag, TaggedItem


@login_required
def front_home(request):
    # Get the 3 last annotated contents
    last_contents = Content.objects.order_by('-last_annotated')[:3]
    # Get the most annotated contents
    most_contents = Content.objects.order_by('-nb_annotation')[:8]
    # Get the active groups
    active_groups = Group.objects.exclude(name=settings.PUBLIC_GROUP_NAME)[:5]
    # Get the main tag list
    front_tags = settings.FRONT_TAG_LIST

    
    is_gecko = ((request.META['HTTP_USER_AGENT'].lower().find("firefox")) > -1);

    return render_to_response("front/front_home.html",
                              {'last_contents': last_contents, 'most_contents':most_contents, 'active_groups':active_groups, 'front_tags':front_tags,
                               'is_gecko': is_gecko},
                              context_instance=RequestContext(request))


@login_required
def group_info(request, group_id):
    # Get the active group
    group = Group.objects.get(id=group_id)
    # list of contents annotated by the group (or everyone)
    everyone = Group.objects.get(name=settings.PUBLIC_GROUP_NAME)
    content_list = get_objects_for_group(group, 'ldt_utils.view_content') | get_objects_for_group(everyone, 'ldt_utils.view_content')
    # Group's users
    users = User.objects.filter(groups__in=[group]).exclude(is_superuser=True)
    
    is_gecko = ((request.META['HTTP_USER_AGENT'].lower().find("firefox")) > -1);

    return render_to_response("front/front_group.html",
                              {'group': group, 'content_list':content_list, 'users':users,
                               'is_gecko': is_gecko},
                              context_instance=RequestContext(request))


@login_required
def all_contents(request):
    # Get the tag parameter if possible
    tag_label = request.GET.get("tag")
    # Get all the public contents group
    if tag_label is None :
        content_list = add_change_attr(request.user, Content.safe_objects.all())
    else :
        content_list = TaggedItem.objects.get_by_model(add_change_attr(request.user, Content.safe_objects.all()), '"'+tag_label+'"')
    # Get the main tag list
    front_tags = settings.FRONT_TAG_LIST
    # Get the all tags list
    tag_cloud = get_content_tags()
    
    is_gecko = ((request.META['HTTP_USER_AGENT'].lower().find("firefox")) > -1);

    return render_to_response("front/front_all_contents.html",
                              {'content_list':content_list, 'tag_label':tag_label, 'front_tags':front_tags, 'tag_cloud':tag_cloud,
                               'is_gecko': is_gecko},
                              context_instance=RequestContext(request))


@login_required
def annot_content(request, content_iri_id, project_id=None, cutting_id=None):
    # Get the wanted content
    content = Content.objects.get(iri_id=content_iri_id)
    # Get the content src to see if it is a youtube video
    youtube_url = None
    if content.src is not None and "youtube.com" in content.src:
        youtube_url = content.src
        
    # If project id is not set, we get the default project for the content
    if project_id is None or project_id == "_":
        front_proj = content.front_project
        if front_proj:
            proj = front_proj
        else:
            # The main project for the content
            proj = Project.safe_objects.filter(contents__in=[content])[0]
    else :
        proj = Project.safe_objects.get(ldt_id=project_id)
    
    # Vars for player
    player_id = "player_project_" + proj.ldt_id
    
    if cutting_id is None :
        json_url = reverse("ldt.ldt_utils.views.json.project_json_id", args=[proj.ldt_id])
    else :
        json_url = reverse("ldt.ldt_utils.views.json.project_json_cutting_id", args=[proj.ldt_id, cutting_id])
    player_width = 550
    player_height = 380
    stream_mode = proj.stream_mode
    if stream_mode != "video":
        stream_mode = 'radio'
    
    is_gecko = ((request.META['HTTP_USER_AGENT'].lower().find("firefox")) > -1);


    return render_to_response("front/front_player.html",
                              {'content': content, 'project':proj, 'player_id': player_id, 
                              'json_url': json_url, 'player_width':player_width, 'player_height':player_height, 'stream_mode':stream_mode, 'youtube_url':youtube_url,
                               'is_gecko': is_gecko},
                              context_instance=RequestContext(request))


@login_required
def search_index(request):
    return ws_search_index(request, front_template=True)


@login_required
def search_listing(request):
    return ws_search_listing(request, front_template=True)


def get_content_tags(limit=None, steps=10):
    if limit is None:
        return Tag.objects.cloud_for_model(Content, steps=steps)
    else :
        return Tag.objects.cloud_for_model(Content, steps=steps)[:limit]


def annotation_preview(request, project_id, content_id, ensemble_id, cutting_id, segment_id):
    
    if project_id == '_':
        project_id = ''
    
    s = get_object_or_404(Segment, iri_id=content_id, project_id=project_id, cutting_id=cutting_id, element_id=segment_id, ensemble_id=ensemble_id)
 
    annotation = {
                  'project_id': s.project_id,
                  'iri_id' : s.iri_id,
                  'ensemble_id' : s.ensemble_id, 
                  'cutting_id' : s.cutting_id,
                  'element_id' : s.ensemble_id,
                  'tags' : s.tags,
                  'title': s.title,
                  'duration': s.duration, 
                  'start_ts': s.start_ts, 
                  'author': s.author,
                  'date': s.date, 
                  'abstract': s.abstract                     
                  }        
    
    mimetype = "application/json; charset=utf-8"
    resp = HttpResponse(mimetype=mimetype)
    resp['Cache-Control'] = 'no-cache, must-revalidate'
    resp['Pragma'] = 'no-cache'
    resp.write(simplejson.dumps(annotation, indent=settings.LDT_JSON_DEFAULT_INDENT))
    
    return resp


    
