from django.conf import settings
from django.contrib.auth.models import Group, User
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.template import RequestContext
from guardian.shortcuts import get_objects_for_group
from ldt.ldt_utils.models import Content, Project
from ldt.ldt_utils.forms import SearchForm
from ldt.ldt_utils.views.workspace import get_search_results
from tagging.models import Tag, TaggedItem
import base64



def front_home(request):
    # Get the 3 last annotated contents
    last_contents = Content.objects.order_by('-stat_annotation__last_annotated').exclude(stat_annotation__nb_annotations=0)[:3]
    # Get the most annotated contents
    most_contents = Content.objects.order_by('-stat_annotation__nb_annotations')[: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
    # 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_home.html",
                              {'last_contents': last_contents, 'most_contents':most_contents, 'active_groups':active_groups, 'front_tags':front_tags,
                               'tag_cloud': tag_cloud, 'is_gecko': is_gecko},
                              context_instance=RequestContext(request))


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



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 = Content.objects.all()
    else :
        content_list = TaggedItem.objects.get_by_model(Content.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))


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/dailymotion video
    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
        
    # 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], state=2)
            if not proj:
                content.create_front_project()
                proj = content.front_project
            else:
                proj = proj[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, 'external_url':external_url,
                               'is_gecko': is_gecko},
                              context_instance=RequestContext(request))


def search_index(request):
    language_code = request.LANGUAGE_CODE[:2]
    nb = 0
    results = []
    search = ''
    field = 'all'
    content_tag = None
    
    sform = SearchForm(request.GET)
    if sform.is_valid():
        search = sform.cleaned_data["search"]
        field = sform.cleaned_data["field"]
        page = sform.cleaned_data["page"] or 1
        # If asked, we filter the request with only the contents tagged with content_tag
        content_tag = sform.cleaned_data["content_tag"]
        content_list = None
        if content_tag is not None and content_tag != "" :
            content_list = TaggedItem.objects.get_by_model(Content.objects.all(), '"'+content_tag+'"')
        results, nb = get_search_results(request, search, field, page, content_list)

    return render_to_response('front/front_search_results.html', {'results': results, 'nb_results' : nb, 'search' : search, 'field': field, 'tag_label':content_tag, 'LDT_MEDIA_PREFIX': settings.LDT_MEDIA_PREFIX, 'colorurl': settings.LDT_MEDIA_PREFIX + 'swf/ldt/pkg/color.xml', 'i18nurl': settings.LDT_MEDIA_PREFIX + 'swf/ldt/pkg/i18n', 'language': language_code, 'baseurl': settings.LDT_MEDIA_PREFIX + 'swf/ldt/'}, context_instance=RequestContext(request))


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]
