from django.conf import settings
from django.contrib.auth.models import Group, User
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.db.models import Count
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.content import get_content_tags
from ldt.ldt_utils.views.workspace import get_search_results
from tagging.models import TaggedItem
from ldt.utils.url import absstatic
import base64

import logging
logger = logging.getLogger(__name__)


def front_home(request):
    # Get the 3 last annotated contents
    last_contents = Content.safe_objects.order_by('-stat_annotation__last_annotated').select_related('stat_annotation').exclude(stat_annotation__nb_annotations=0)[:3]
    # Get the most annotated contents
    most_contents = Content.safe_objects.order_by('-stat_annotation__nb_annotations').select_related('stat_annotation')[:8]
    # Get the active groups
    active_groups = Group.objects.select_related("profile").annotate(nb_users=Count("user")).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 page number parameter if possible
    page = request.GET.get("page") or 1
    # Get the medias title filter if possible
    media_title = request.GET.get("title")
    tag_label = None
    if media_title is None :
        # 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.safe_objects.all().select_related('stat_annotation')
        else :
            content_list = TaggedItem.objects.get_by_model(Content.safe_objects.all().select_related('stat_annotation'), '"'+tag_label+'"')
    else :
        content_list = Content.safe_objects.filter(title__icontains=media_title).select_related('stat_annotation')
    
    
    nb = settings.LDT_FRONT_MEDIA_PER_PAGE
    if page=="x":
        nb = content_list.count()
    
    paginator = Paginator(content_list, nb)
    try:
        results = paginator.page(page)
    except (EmptyPage, InvalidPage):
        results = paginator.page(paginator.num_pages)
    
    # 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",
                              {'results':results, 'tag_label':tag_label, 'media_title':media_title, '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
    annotation_block = True
    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 == "_":
        proj = content.get_or_create_front_project()
    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, 'annotation_block':annotation_block},
                              context_instance=RequestContext(request))


def search_index(request):
    language_code = request.LANGUAGE_CODE[:2]
    nb = 0
    results = []
    search = ''
    field = 'all'
    content_tag = None
    colorurl=absstatic(request, "ldt/swf/ldt/pkg/color.xml")
    i18nurl=absstatic(request, "ldt/swf/ldt/pkg/i18n")
    baseurl=absstatic(request, "ldt/swf/ldt/")
    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, nb_segment = get_search_results(request, search, field, page, content_list)

    return render_to_response('front/front_search_results.html', {'results': results, 'nb_results' : nb, 'nb_segment':nb_segment, 'search' : search, 'field': field, 'tag_label':content_tag, 'colorurl': colorurl, 'i18nurl': i18nurl, 'language': language_code, 'baseurl': baseurl}, context_instance=RequestContext(request))



