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

@author: ymh
'''
from django.conf import settings
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.http import HttpResponse
from hp.models import VideoKCRel
import logging
import requests
import urlparse

logger = logging.getLogger(__name__)


def all_videos(request):
    
    #get all videos
    #render
    url = settings.LDT_API_URL + "contents/"
    #limit=20&offset=20
    r = requests.get(url)
        
    
    
    results = r.json
        
    for content in results.get('objects', []):
        url_parts = urlparse.urlparse(content.get('image',''))
        if not url_parts.netloc:
            content['image'] = settings.LDT_DOMAIN + content.get('image','')
        
    return render_to_response('hp/all_videos.html',{'results':results}, 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
    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]
        
    kc_id = None
    topic_id = None
    
    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
    
    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):
    
    url = settings.KC_URL + path
    
    data = request.POST if request.method=="POST" else {}
    
    r = requests.request(request.method, url, data=data)
    
    return HttpResponse(content=r.text, content_type='application/json;charset=UTF-8')
    