# -*- coding: utf-8 -*-
from django.conf import settings
from django.http import HttpResponse, HttpResponseForbidden
from django.shortcuts import get_object_or_404, get_list_or_404
from django.utils import simplejson
from django.utils.html import escape
from django.utils.translation import ugettext as _
from ldt.indexation import get_results_with_context
from ldt.ldt_utils.models import Project
from ldt.ldt_utils.projectserializer import ProjectSerializer
from ldt.ldt_utils.views.lignesdetemps import search_ldt
from datetime import datetime
import ldt.auth as ldt_auth
import lxml.etree


def project_json_id(request, id): 
    
    project = get_object_or_404(Project.safe_objects, ldt_id=id)

    return project_json(request, project, False)

def project_json_cutting_id(request, id, cutting_id):

    project = get_object_or_404(Project.safe_objects, ldt_id=id)

    return project_json(request, project, first_cutting=cutting_id)

def project_json_externalid(request, id): 
        
    res_proj = get_list_or_404(Project.safe_objects.order_by('-modification_date'), contents__external_id=id) #@UndefinedVariable
    
    return project_json(request, res_proj[0], False)



def project_json(request, project, serialize_contents=True, first_cutting=None):
    
    if not ldt_auth.check_access(request.user, project):
        return HttpResponseForbidden(_("You can not access this project"))
        
    mimetype = request.REQUEST.get("mimetype")
    if mimetype is None:
        mimetype = "application/json; charset=utf-8"
    else:
        mimetype = mimetype.encode("utf-8")
    if "charset" not in mimetype:
        mimetype += "; charset=utf-8" 
    resp = HttpResponse(mimetype=mimetype)
    resp['Cache-Control'] = 'no-cache, must-revalidate'
    resp['Pragma'] = 'no-cache'
    
    indent = request.REQUEST.get("indent")
    if indent is None:
        indent = settings.LDT_JSON_DEFAULT_INDENT
    else:
        indent = int(indent)
    
    callback = request.REQUEST.get("callback")
    escape_str = request.REQUEST.get("escape")
    escape_bool = False
    if escape_str:
        escape_bool = {'true': True, 'false': False, "0": False, "1": True}.get(escape_str.lower())
        
        
    ps = ProjectSerializer(project, serialize_contents, first_cutting=first_cutting)
    project_dict = ps.serialize_to_cinelab()
    
    json_str = simplejson.dumps(project_dict, ensure_ascii=False, indent=indent)
    
    if callback is not None:
        json_str = "%s(%s)" % (callback, json_str)
    
    if escape_bool:
        json_str = escape(json_str)
    
    resp.write(json_str)

    return resp



def mashup_by_tag(request):
    # do we indent ?
    indent = request.REQUEST.get("indent")
    if indent is None:
        indent = settings.LDT_JSON_DEFAULT_INDENT
    else:
        indent = int(indent)
    # do we escape ?
    escape_str = request.REQUEST.get("escape")
    escape_bool = False
    if escape_str:
        escape_bool = {'true': True, 'false': False, "0": False, "1": True}.get(escape_str.lower())
    
    # We search
    s = request.REQUEST.get("tag")
    if s:
        # We get the projects with all the segments
        project_xml, results = search_ldt(request, "tags", s, None, True, False)
        project = Project()
        project.ldt = lxml.etree.tostring(project_xml, pretty_print=True)
        # Needed datas for jsonification
        now = datetime.now()
        project.modification_date = project.creation_date = now
        #return HttpResponse(lxml.etree.tostring(project_xml, pretty_print=True), mimetype="text/xml;charset=utf-8")
        ps = ProjectSerializer(project, from_contents=False)
        mashup_dict = ps.serialize_to_cinelab()
        # Now we build the mashup with the good segments (the ones between in and out)
        if results:
            tc_in = 0
            if request.REQUEST.get("in") :
                tc_in = float(request.REQUEST.get("in"))
            tc_out = float('inf')
            if request.REQUEST.get("out") :
                tc_out = float(request.REQUEST.get("out"))
            # Since the timecodes are saved as strings, we filter after calculating float in and out. Timecodes are in milliseconds
            mashup_list = {
                "items": [],
                "meta": {
                    "dc:contributor": "IRI",
                    "dc:creator": "IRI",
                    "dc:title": "Generated mashup with tag '"+s+"'",
                    "dc:modified": now.isoformat(),
                    "dc:created": now.isoformat(),
                    "listtype": "mashup",
                    "dc:description": ""
                },
                "id": "generated_mashup_list"
            }
            #filtered_results = []
            for res in results:
                cur_in = float(res["start_ts"])
                cur_out = cur_in + float(res["duration"])
                if tc_in<=cur_in and cur_out<=tc_out:
                     #filtered_results.append(res)
                     mashup_list["items"].append(res["element_id"])
            mashup_dict["lists"].append(mashup_list)
    
    #mashup_dict["escape_bool"] = escape_bool
    #mashup_dict["indent"] = indent
    
    json_str = simplejson.dumps(mashup_dict, ensure_ascii=False, indent=indent)
    if escape_bool:
        json_str = escape(json_str)
    
    resp = HttpResponse(mimetype="application/json; charset=utf-8")
    resp['Cache-Control'] = 'no-cache, must-revalidate'
    resp['Pragma'] = 'no-cache'
    resp.write(json_str)
    
    return resp
