import logging

from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import (HttpResponseForbidden, HttpResponseNotFound,
    HttpResponseRedirect)
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.views.generic import View

from ldt.utils.web_url_management import get_web_url
from utils import get_datas_for_embed


logger = logging.getLogger(__name__)

class ConfigView(View):
    """
        Meta class for generating metadataplayer config view. 
        This class is supposed to be inherited with corresponding template_name and iframe_base_url (see v1 and v2)
        The relevant methods also have to be redefined if necessary
    """
    template_name = ""
    iframe_base_url = ""
    
    def get(self, request):
        print(request.GET)
        json_url = request.GET.get("json_url")
        player_id = request.GET.get("player_id")
        ldt_id = request.GET.get("ldt_id")
        rend_dict = get_datas_for_embed(request, json_url, player_id, ldt_id, self.iframe_base_url)
        embed_rendered = dict((typestr,
                               (lambda s:escape(render_to_string("ldt/ldt_utils/partial/embed_%s.html" % (s), rend_dict, context_instance=RequestContext(request))))(typestr))
                               for typestr in ('seo_body', 'seo_meta', 'links'))
        json_url_concatenate = str(reverse("api_content_all_projects", kwargs={'api_name': '1.0', 'resource_name': 'contents', 'iri_id': rend_dict["content_id"]}))
        # add filter
        group_id = request.GET.get("group")
        if group_id is not None :
            json_url_concatenate += "?group=" + group_id
        rend_dict["json_url_concatenate"] = json_url_concatenate
        rend_dict['embed_rendered'] = embed_rendered
        return render_to_response(self.template_name, rend_dict, context_instance=RequestContext(request))
    
    
class IframeView(View):
    """
        Meta class for generating metadataplayer iframe view. 
        This class is supposed to be inherited with corresponding template_name and iframe_base_url (see v1 and v2)
        The relevant methods also have to be redefined if necessary
    """
    template_name = ""
    iframe_base_url = ""
    
    def get(self, request):
        content_id = request.GET.get("content_id")
        project_id = request.GET.get("project_id")
        if not project_id:
            try:
                content = Content.safe_objects.get(iri_id=content_id)
            except:
                return HttpResponseForbidden(_("The content does not exists or you are not allowed to access this content"))
            project = content.get_or_create_front_project()
            project_id = project.ldt_id
        if not project_id :
            return HttpResponseForbidden(_("Parameters project_id or content_id must be given in the url"))
            
        json_url = reverse("projectjson_id", kwargs={'id':project_id})
        player_id = "player_project_" + project_id
        ldt_id = project_id
        rend_dict = get_datas_for_embed(request, json_url, player_id, ldt_id, self.iframe_base_url)
        
        # Test if concatenated projects has been asked
        concatenate_projects = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("concatenate_projects", "").lower())
        if concatenate_projects:
            json_url = reverse("api_content_all_projects", kwargs={'api_name': '1.0', 'resource_name': 'contents', 'iri_id': content_id})
            # add filter
            group_id = request.GET.get("group")
            if group_id is not None :
                json_url += "?group=" + group_id
            rend_dict["json_url"] = json_url
        
        # Manage iframe options
        if request.GET.has_key("player_height"):
            rend_dict["player_height"]=request.GET.get("player_height")
        else:
            rend_dict["player_height"]=300
        if request.GET.has_key("player_width"):
            rend_dict["player_width"]=request.GET.get("player_width")
        else:
            rend_dict["player_width"]=550
        if request.GET.has_key("polemic"):
            rend_dict["polemic"] = request.GET.get("polemic")
            if request.GET.has_key("polemic_defaultColor"):
                rend_dict["polemic_defaultColor"] = request.GET.get("polemic_defaultColor")
            else:
                rend_dict["polemic_defaultColor"]="585858"
            if request.GET.has_key("polemic_foundColor"):
                rend_dict["polemic_foundColor"] = request.GET.get("polemic_foundColor")
            else:
                rend_dict["polemic_foundColor"]="fc00ff"
            if request.GET.has_key("polemic_okColor"):
                rend_dict["polemic_okColor"] = request.GET.get("polemic_okColor")
            else:
                rend_dict["polemic_okColor"] = "1d973d"
            if request.GET.has_key("polemic_koColor"):
                rend_dict["polemic_koColor"] = request.GET.get("polemic_koColor")
            else:
                rend_dict["polemic_koColor"]="ce0a15"
            if request.GET.has_key("polemic_refColor"):
                rend_dict["polemic_refColor"] = request.GET.get("polemic_refColor")
            else:
                rend_dict["polemic_refColor"] = "c5a62d"
            if request.GET.has_key("polemic_qColor"):
                rend_dict["polemic_qColor"] = request.GET.get("polemic_qColor")
            else:
                rend_dict["polemic_qColor"] = "036aae"
            if request.GET.has_key("polemics_list"):
                try:
                    # Very rough : has to be something like 
                    # [{"name":"OK","keywords":["%2B%2B"],"color":"%23DDDDDD"},{"name":"KO","keywords":["--"],"color":"%23AAAAAA"},{"name":"REF","keywords":["==","http://"],"color":"%23777777"},{"name":"Q","keywords":["?"],"color":"%23333333"}]
                    pd = request.GET.get("polemics_list")
                except:
                    pd = False
                rend_dict["polemics_list"] = pd
            else:
                rend_dict["polemics_list"] = False
            if request.GET.has_key("polemic__max_elements"):
                try:
                    pme = int(request.GET.get("polemic__max_elements"))
                except:
                    pme = 20
                rend_dict["polemic__max_elements"] = pme
            else:
                rend_dict["polemic__max_elements"] = 20
                
        if request.GET.has_key("autostart"):
            rend_dict["autostart"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("autostart").lower())
        else : 
            rend_dict["autostart"] = True
        if request.GET.has_key("createannotation"):
            rend_dict["createannotation"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("createannotation").lower())
        if request.GET.has_key("show_mic_record"):
            rend_dict["show_mic_record"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("show_mic_record").lower())
            if rend_dict["show_mic_record"]:
                rend_dict["createannotation"]=True
        rend_dict["createannotation_polemics"] = True
        if request.GET.has_key("createannotation_polemics"):
            rend_dict["createannotation_polemics"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("createannotation_polemics").lower())
        if request.GET.has_key("annotations_list"):
            rend_dict["annotations_list"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("annotations_list").lower())
            rend_dict["player_width"] = 550
        if request.GET.has_key("tag_titles"):
            rend_dict["tag_titles"] = request.GET.get("tag_titles")
        if request.GET.has_key("sparkline"):
            rend_dict["sparkline"] = request.GET.get("sparkline")
            if request.GET.has_key("sparkline_lineColor"):
                rend_dict["sparkline_lineColor"] = request.GET.get("sparkline_lineColor")
            else:
                rend_dict["sparkline_lineColor"] = "7492b4"
            if request.GET.has_key("sparkline_fillColor"):
                rend_dict["sparkline_fillColor"] = request.GET.get("sparkline_fillColor")
            else:
                rend_dict["sparkline_fillColor"] = "aeaeb8"
        if request.GET.has_key("slideshare"):
            rend_dict["slideshare"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("slideshare").lower())
        if request.GET.has_key("social"):
            rend_dict["social"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("social").lower())     
            if request.GET.has_key("show_url"):
                rend_dict["show_url"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("show_url").lower())
            else:
                rend_dict["show_url"] = True    
            if request.GET.has_key("show_twitter"):
                rend_dict["show_twitter"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("show_twitter").lower())     
            else:
                rend_dict["show_twitter"] = True
            if request.GET.has_key("show_fb"):
                rend_dict["show_fb"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("show_fb").lower())     
            else:
                rend_dict["show_fb"] = True
            if request.GET.has_key("show_gplus"):
                rend_dict["show_gplus"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("show_gplus").lower())     
            else:
                rend_dict["show_gplus"] = True
            if request.GET.has_key("show_mail"):
                rend_dict["show_mail"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("show_mail").lower())     
            else:
                rend_dict["show_mail"] = True
        if request.GET.has_key("annotation"):
            rend_dict["annotation"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("annotation").lower())
        if request.GET.has_key("tweet"):
            rend_dict["tweet"] ={'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("tweet").lower())
        if request.GET.has_key("segments"):
            rend_dict["segments"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("segments").lower())
        else:
            rend_dict["segments"] = True
        if request.GET.has_key("tagcloud"):
            rend_dict["tagcloud"] = {'true': True, 'false': False, "0": False, "1": True}.get(request.GET.get("tagcloud").lower())
        return render_to_response(self.template_name, rend_dict, context_instance=RequestContext(request))
        