import logging
import json

from django.core.urlresolvers import reverse_lazy, reverse
from django.http import HttpResponseForbidden
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _

from ldt import settings
from ldt.ldt_utils.models import Content
from ldt.ldt_utils.views.embed.meta import ConfigView, IframeView
from ldt.ldt_utils.views.embed.utils import get_datas_for_embed

from ldt.utils.input import parse_bool


logger = logging.getLogger(__name__)

class ConfigViewV4(ConfigView):
    template_name = "ldt/ldt_utils/embed/v4/mdplayer_config.html"
    iframe_base_url = reverse_lazy("embed_iframe_v4")#, urlconf="ldtplatform.urls")

class IframeViewV4(IframeView):
    template_name = "ldt/ldt_utils/embed/v4/iframe.html"
    iframe_base_url = reverse_lazy("embed_iframe_v4")#, urlconf="ldtplatform.urls")

    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 = parse_bool(request.GET.get("concatenate_projects", ""))
        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
        rend_dict["player_height"]=request.GET.get("player_height", 300)
        rend_dict["player_width"]=request.GET.get("player_width", 550)

        if request.GET.has_key("polemic"):
            rend_dict["polemic"] = True
            if request.GET.get("polemic") == "all":
                rend_dict["polemic_annotation_types"] = []
            else:
                polemic_annotation_types_list = request.GET.get("polemic").split(",")
                rend_dict["polemic_annotation_types"] = polemic_annotation_types_list
            rend_dict["polemic_defaultColor"] = request.GET.get("polemic_defaultColor", "585858")
            rend_dict["polemic_foundColor"] = request.GET.get("polemic_foundColor", "fc00ff")
            rend_dict["polemic_version"] = request.GET.get("polemic_version", "1")

            polemic_protocol_def = settings.POLEMIC_PROTOCOL_DEFINITION or {}
            polemic_protocol_str = json.dumps(polemic_protocol_def, separators=(',',':'))
            rend_dict["polemics_list"] = request.GET.get("polemics_list", polemic_protocol_str)
            try:
                pme = int(request.GET.get("polemic_max_elements", 50))
            except:
                pme = 50
            rend_dict["polemic_max_elements"] = pme

        rend_dict["autostart"] = parse_bool(request.GET.get("autostart", "false"), False)
        rend_dict["createannotation"] = parse_bool(request.GET.get("createannotation", "false"), False)

        if request.GET.has_key("show_mic_record"):
            rend_dict["show_mic_record"] = parse_bool(request.GET.get("show_mic_record"))
            if rend_dict["show_mic_record"]:
                rend_dict["createannotation"]=True
            if request.GET.has_key("createannotation_annotation_types"):
                segments_annotation_types_list = request.GET.get("createannotation_annotation_types").split(",")
                rend_dict["createannotation_annotation_types"] = segments_annotation_types_list
            else:
                rend_dict["createannotation_annotation_types"] = False

        rend_dict["createannotation_polemics"] = True

        if request.GET.has_key("createannotation_polemics"):
            rend_dict["createannotation_polemics"] = parse_bool(request.GET.get("createannotation_polemics"))

        if request.GET.has_key("annotations_list"):
            rend_dict["annotations_list"] = parse_bool(request.GET.get("annotations_list"))
            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")
            rend_dict["sparkline_lineColor"] = request.GET.get("sparkline_lineColor", "7492b4")
            rend_dict["sparkline_fillColor"] = request.GET.get("sparkline_fillColor", "aeaeb8")

        if request.GET.has_key("slideshare"):
            rend_dict["slideshare"] = parse_bool(request.GET.get("slideshare"))

        if request.GET.has_key("social"):
            rend_dict["social"] = parse_bool(request.GET.get("social"))
            rend_dict["show_url"] = parse_bool(request.GET.get("show_url", "true"), True)
            rend_dict["show_twitter"] = parse_bool(request.GET.get("show_twitter", "true"), True)
            rend_dict["show_fb"] = parse_bool(request.GET.get("show_fb", "true"), True)
            rend_dict["show_gplus"] = parse_bool(request.GET.get("show_gplus", "true"),True)
            rend_dict["show_mail"] = parse_bool(request.GET.get("show_mail", "true"), True)

        if request.GET.has_key("annotation"):
            rend_dict["annotation"] = parse_bool(request.GET.get("annotation").lower())
        if request.GET.has_key("tweet"):
            rend_dict["tweet"] =parse_bool(request.GET.get("tweet").lower())
        rend_dict["segments"] = parse_bool(request.GET.get("segments", "true"), True)
        if request.GET.has_key("segments_annotation_types"):
            rend_dict["segments_annotation_types"] = request.GET.get("segments_annotation_types").split(",")
        else:
            rend_dict["segments_annotation_types"] = "false"
        if request.GET.has_key("multisegments"):
            rend_dict["multisegments"] = parse_bool(request.GET.get("multisegments"))
        if request.GET.has_key("tagcloud"):
            rend_dict["tagcloud"] = parse_bool(request.GET.get("tagcloud"))

        return render_to_response(self.template_name, rend_dict, context_instance=RequestContext(request))
