# -*- coding: utf-8 -*-
'''
Created on Nov 11, 2012

@author: ymh
'''
from django.conf import settings
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from hp.models import VideoKCRel
from hp.utils import get_all_objects
import logging
import requests
import urlparse

logger = logging.getLogger(__name__)


def all_videos(request):
    
    url = "%scontents/" % (settings.LDT_API_URL)
    
    request_params = {'limit' : settings.LDT_MAX_FETCH, 'order_by': 'title'}
    
    search = request.REQUEST.get("search", None)
    if search:
        search = search.strip()
        request_params['title__icontains'] = search

    #pagination TODO : implement a lazy loader     
    contents = get_all_objects(url, request_params, 'front_project')

    for content in contents:
        url_parts = urlparse.urlparse(content.get('image',''))
        if not url_parts.netloc:
            content['image'] = settings.LDT_DOMAIN + content.get('image','')

    paginator = Paginator(contents, settings.PER_PAGE, 0, True)

    page = request.GET.get('page',1)
    if page == 'last':
        page = paginator.num_pages
    try:
        results = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        results = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        results = paginator.page(paginator.num_pages)
    
    if search:
        search_param = "&search=%s" % search
        search_param_first = "?search=%s" % search
    else:
        search_param = ""
        search_param_first = ""
    
    return render_to_response('hp/all_videos.html',{'results':results, 'search': search, 'search_param': search_param, 'search_param_first': search_param_first}, context_instance=RequestContext(request))
    

def show_video_details(request, content_id):
    
    url_content = settings.LDT_API_URL + "contents/%s" % content_id
    
    r_content = requests.get(url_content)
        
    logger.debug(r_content.text)
    
    content = r_content.json
        
    kc_id = None
    topic_id = None
    project_id = ""
    
    kc_relation_list = list(VideoKCRel.objects.filter(iri_id=content_id)[:1])
    
    if len(kc_relation_list) > 0:
        kc_id = kc_relation_list[0].graph_id
        topic_id = kc_relation_list[0].topic_id
        project_id = kc_relation_list[0].project_id

    logger.debug("%s : %s : %s" % (kc_id, topic_id, repr(project_id)))

    if not project_id:
        project_url = content['front_project']
        project_path = urlparse.urlparse(project_url).path    
        project_id = ""
        if project_path:
            project_path_parts = project_path.split("/")
            project_id = project_path_parts[-1] if project_path_parts[-1] else project_path_parts[-2]
    
    logger.debug("%s : %s : %s" % (kc_id, topic_id, repr(project_id)))
    
    return render_to_response(
        'hp/video_player.html',
        {'content':content, 'project_id': project_id, 'kc_id': kc_id, 'topic_id': topic_id},
        context_instance=RequestContext(request))


def kc_proxy(request, path):
    
    r = requests.request(request.method, settings.KC_URL + path, data=request.POST, params=request.GET)
    
    logger.debug("Proxy r url : " + r.url)
    logger.debug("Proxy r method : " + r.request.method)
    logger.debug("Proxy r full url : " + r.request.full_url)
    logger.debug("Proxy r status : " + str(r.status_code))
    logger.debug("Proxy r text : " + r.text)
        
    return HttpResponse(content=r.text, content_type='application/json;charset=UTF-8')
    