from django.conf import settings
from django.contrib.auth import get_user_model
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
from django.db.models import Count
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from ldt.ldt_utils.forms import SearchForm
from ldt.ldt_utils.models import Content, Project
from ldt.ldt_utils.views.group import get_group_projects
from ldt.ldt_utils.views.workspace import get_search_results
from ldt.utils.url import static
import logging
from guardian.shortcuts import get_objects_for_group
from ldt.indexation import get_results_with_context

User = get_user_model()
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
    
    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))


def group_list(request):
    
    # Get the active group
    group_list = Group.objects.select_related("profile").exclude(name=settings.PUBLIC_GROUP_NAME).order_by('name')
    
    is_gecko = ((request.META['HTTP_USER_AGENT'].lower().find("firefox")) > -1)

    return render_to_response("front/front_groups.html",
                              {'group_list':group_list,
                               'is_gecko': is_gecko},
                              context_instance=RequestContext(request))

@login_required
def group_info(request, group_id):
    
    # Get the active group
    group = Group.objects.select_related("profile").get(id=group_id)
    proj_title = request.GET.get("title")
    # Get the projects for this group
    project_list = get_group_projects(request.user, group_id, False, False)
    if not type(project_list) is list:
        project_list = project_list.prefetch_related('contents').select_related("owner").filter(state=2)
        if proj_title is not None:
            project_list = project_list.filter(title__icontains=proj_title)
    
    nb = settings.LDT_FRONT_PROJECTS_PER_PAGE
    page = request.GET.get("page") or 1
    if page=="x":
        nb = project_list.count()
    
    paginator = Paginator(project_list, nb)
    try:
        results = paginator.page(page)
    except (EmptyPage, InvalidPage):
        results = paginator.page(paginator.num_pages)
    
    # 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':None, 'results':results, 'users':users, 'project_title':proj_title,
                               'projects': True, 'is_gecko': is_gecko},
                              context_instance=RequestContext(request))

@login_required
def group_medias(request, group_id):
    group = get_object_or_404(Group, id=group_id)
    
    content_list = get_objects_for_group(group, '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, 'results':None, 'users':users,
                               'projects': False, '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+'"')
            content_list = Content.safe_objects.select_related('stat_annotation').filter(tags__name__in=[tag_label])
    else :
        #content_list = Content.safe_objects.filter(title__icontains=media_title).select_related('stat_annotation')
        content_searched = get_results_with_context(Content, "all", media_title)
        content_list = Content.objects.filter(pk__in=[c['indexation_id'] for c in content_searched]).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
    
    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, '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", kwargs={'id' : proj.ldt_id})
    else:
        json_url = reverse("ldt.ldt_utils.views.json.project_json_cutting_id", kwargs={'id':proj.ldt_id, 'cutting_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 all_projects_for_media(request, content_iri_id):
        # 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 = False
    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
               
    # Vars for player
    player_id = "player_project_anything"
    
    json_url = reverse("api_content_all_projects", kwargs={'api_name': '1.0', 'resource_name': 'contents', 'iri_id': content_iri_id})
    
    # add filter
    group_id = request.GET.get("group")
    if group_id is not None :
        json_url += "?group=" + group_id
    # add parameter to remove segment with duration = 0
    remove_zero_duration = False
    remove_zero_param = request.GET.get("remove_zero_duration")
    if remove_zero_param is not None :
        remove_zero_duration = {'true': True, 'false': False, "0": False, "1": True}.get(remove_zero_param.lower())
    
    player_width = 854
    player_height = 480
    stream_mode = "video"
    
    is_gecko = ((request.META['HTTP_USER_AGENT'].lower().find("firefox")) > -1)


    return render_to_response("front/front_player.html",
                              {'content': content, '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, 'toggle_multisegments':True, 'remove_zero_duration':remove_zero_duration},
                              context_instance=RequestContext(request))



def search_index(request):
    language_code = request.LANGUAGE_CODE[:2]
    nb = 0
    results = []
    search = ''
    field = 'all'
    content_tag = None
    colorurl=static("ldt/swf/ldt/pkg/color.xml")
    i18nurl=static("ldt/swf/ldt/pkg/i18n")
    baseurl=static("ldt/swf/ldt/")
    sform = SearchForm(request.GET)
    content_results = None
    more_contents = False
    
    # Now we handle the segment search
    if sform.is_valid():
        search = sform.cleaned_data["search"]
        field = sform.cleaned_data["field"]
        # If the request has a page indicated, we are in segment search
        if "page" not in request.GET:
            # If not, we are in the first page of results, so we display the first contents
            content_searched = get_results_with_context(Content, field, search)
            if len(content_searched) > settings.LDT_MEDIA_IN_RESULTS_PAGE :
                more_contents = True
                content_searched = content_searched[:settings.LDT_MEDIA_IN_RESULTS_PAGE]
            content_results = Content.objects.filter(pk__in=[c['indexation_id'] for c in content_searched]).select_related('stat_annotation')
        
        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+'"')
            content_list = Content.safe_objects.filter(tags__name__in=[content_tag])
        results, nb, nb_segment = get_search_results(request, search, field, page, content_list)
        
        # If there was no answer, we check if a search with content's title works
        if nb==0:
            nb = Content.safe_objects.filter(title__icontains=search).count()
            nb_segment = 0
            content_results = Content.safe_objects.filter(title__icontains=search).select_related('stat_annotation')[:settings.LDT_MEDIA_IN_RESULTS_PAGE]
    else:
        results, nb, nb_segment = None, 0, 0
        

    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,
                                'content_results': content_results, 'more_contents': more_contents,
                                }, context_instance=RequestContext(request))


    