# -*- coding: utf-8 -*-
'''
Created on Jul 01, 2014

@author: tc
'''
from datetime import datetime
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView, View
from hdabo.models import Tag
from hdalab.models.renkan import HdalabRenkan
from hdalab.views.ajax import filter_generic
from renkanmanager.models import Renkan
from renkanmanager.utils import LineNodePlacer, renkan_copier, renkan_deleter
from renkanmanager.views import RenkanGetPut
import json
import uuid


import logging
from django.core.urlresolvers import reverse
logger = logging.getLogger(__name__)


class ProfileHome(TemplateView):
    
    template_name = "profile_home.html"
    
    def get_context_data(self, **kwargs):
        context = super(ProfileHome, self).get_context_data(**kwargs)
        context['renkan_list'] = HdalabRenkan.objects.select_related("renkan").filter(renkan__owner=self.request.user).order_by("-renkan__modification_date")
        return context


class RenkanPublicList(TemplateView):
    
    template_name = "renkan_list.html"
    
    def get_context_data(self, **kwargs):
        context = super(RenkanPublicList, self).get_context_data(**kwargs)
        context['renkan_list'] = HdalabRenkan.objects.select_related("renkan").filter(state=HdalabRenkan.PUBLISHED).order_by("-renkan__modification_date")
        return context



class RenkanNew(View):
    
    def get(self, request):
        
        rk = Renkan()
        rk_id = unicode(uuid.uuid1())
        rk.rk_id = rk_id
        rk.owner = request.user
        rk.content = '{}'
        rk.title = "Nouveau Renkan "
        rk.save()
        hr = HdalabRenkan()
        hr.renkan = rk
        from random import randrange
        hr.state = randrange(4) + 1
        hr.save()
        
        return redirect("%s?rk_id=%s" % (reverse('renkan_edit'), rk_id))



class RenkanEdit(TemplateView):
    
    template_name="renkan_edit.html"
    
    def get_context_data(self, **kwargs):
        context = super(RenkanEdit, self).get_context_data(**kwargs)
        # If a renkan id is set
        rk_id = self.request.GET.get("rk_id", "")
        if rk_id!="":
            rk = get_object_or_404(Renkan, rk_id=rk_id)
            if rk.owner!=self.request.user:
                raise Exception("You are not allowed to edit this renkan")
        
        return context



class HdalabRenkanGetPut(RenkanGetPut):
    
    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(HdalabRenkanGetPut, self).dispatch(*args, **kwargs)
    
    def get(self, request):
        
        # If a renkan id is set
        rk_id = request.GET.get("rk_id", "")
        if rk_id!="":
            rk = get_object_or_404(Renkan, rk_id=rk_id)
            return HttpResponse(rk.content, content_type="application/json")
        
        # Otherwise we build the datas
        # Get tags and countries
        labels = request.GET.get("label", "").split(",")
        countries = request.GET.get("country", "").split(",")
        # Tags arrive with french label, countries with dbpedia uri
        label_list = [t for t in labels if t!=""]
        country_list = [c for c in countries if c!=""]
        all_tags = Tag.objects.filter( Q(label__in=label_list) | Q(dbpedia_uri__in=country_list) ).select_related("dbpedia_fields")
        
        
        now = datetime.now().strftime("%Y-%m-%d %H:%M")
        
        content = {
          "id": unicode(uuid.uuid1()),
          "title": "",
          "description": "(empty description)",
          "created": now,
          "updated": now,
          "nodes": [],
          "edges": [],
          "views": [],
          "users": [],
        }
        
        
        # Get datasheets from ajax filter search
        filter_output = filter_generic(request.GET.get('lang',request.LANGUAGE_CODE), None, ",".join(label_list), ",".join(country_list))
        filter_output = json.loads(filter_output)
        #logger.debug("COUCOU")
        #logger.debug(json.dumps(filter_output, indent=2))
        #return HttpResponse(json.dumps(filter_output, indent=2), content_type="application/json")
        
        # Prepare other tags
        related_tags = []
        all_labels = [t.label for t in all_tags]
        title = "Recherche " + ", ".join(all_labels)
        content["title"] = title
        related_tags_dict = {}
        for c in filter_output["contents"]:
            c["id"] = unicode(uuid.uuid1())
            related_tags_dict[c["id"]] = []
            for t in c["tags"]:
                if t["label"] not in all_labels and t["order"]<6:
                    thumbnail_url = ""
                    for tt in filter_output["tags"]:
                        if tt["label"]==t["label"]:
                            thumbnail_url = tt["thumbnail"]
                    related_tags.append({"label": t["label"], "thumbnail":thumbnail_url, "id":t["id"]})
                    all_labels.append(t["label"])
                    related_tags_dict[c["id"]].append(t["id"])
        #return HttpResponse(json.dumps({"t":related_tags_label}, indent=2), content_type="application/json")
        
        # Prepare Node placer :
        np = LineNodePlacer()
        np.init({"tags": (1, len(all_tags)), "datasheet": (2, len(filter_output["contents"])), "related": (3, len(related_tags))})
        
        project_id = unicode(uuid.uuid1())
        
        for t in all_tags:
            content["nodes"].append({
              "id": unicode(uuid.uuid1()),
              "title": t.label,
              "description": t.dbpedia_uri,
              "uri": t.dbpedia_uri,
              "position": np.get_place("tags"),
              "image": t.dbpedia_fields.thumbnail if hasattr(t, 'dbpedia_fields') and t.dbpedia_fields and t.dbpedia_fields.thumbnail else None,
              "size": 0,
              "project_id": project_id,
              "color": None,
              #"created_by": "roster_user-84fe909f-ba37-48e6-a25f-9d2f129a95b7"
            })
        
        for c in filter_output["contents"]:
            content["nodes"].append({
              "id": c["id"],
              "title": c["title"],
              "description": c["description"],
              "uri": c["url"],
              "position": np.get_place("datasheet"),
              "image": None,
              "size": 0,
              "project_id": project_id,
              "color": "#FF0033",
              #"created_by": "roster_user-84fe909f-ba37-48e6-a25f-9d2f129a95b7"
            })
        
        for t in related_tags:
            content["nodes"].append({
              "id": t["id"],
              "title": t["label"],
              "description": "",
              "uri": "",
              "position": np.get_place("related"),
              "image": t["thumbnail"],
              "size": 0,
              "project_id": project_id,
              "color": "#00FF33",
              #"created_by": "roster_user-84fe909f-ba37-48e6-a25f-9d2f129a95b7"
            })
        
        for c_id in related_tags_dict:
            for tag_id in related_tags_dict[c_id]:
                content["edges"].append({
                    "id": unicode(uuid.uuid1()),
                    "title": "",
                    "description": "",
                    "uri": "",
                    "color": None,
                    "from": c_id,
                    "to": tag_id,
                    "project_id": project_id,
                    #"created_by": "de68xf75y6hs5rgjhgghxbm217xk"
                })
        
        response = json.dumps(content)
        
        if request.user.is_authenticated():
            rk = Renkan()
            rk.rk_id = unicode(uuid.uuid1())
            rk.title = title
            rk.content = response
            rk.owner = request.user
            rk.save()
            hr = HdalabRenkan()
            hr.renkan = rk
            hr.state = HdalabRenkan.EDITION
            hr.save()
        
        return HttpResponse(response, content_type="application/json")




class HdalabRenkanCopy(View):
    
    def get(self, request, rk_id):
        rk = renkan_copier(request.user, rk_id)
        hr = HdalabRenkan()
        hr.renkan = rk
        hr.state = HdalabRenkan.EDITION
        hr.save()
        if "next" in request.GET:
            return redirect(request.GET["next"])
        return redirect(reverse('profile_home'))



class HdalabRenkanDelete(View):
    
    def get(self, request, rk_id):
        renkan_deleter(request.user, rk_id)
        if "next" in request.GET:
            return redirect(request.GET["next"])
        return redirect(reverse('profile_home'))
    