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

@author: tc
'''
from datetime import datetime
from django.db.models import Q
from django.http.response import HttpResponse
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
from hdabo.models import Tag
from hdalab.utils import LineNodePlacer
from hdalab.views.ajax import filter_generic
import json
import uuid

import logging
logger = logging.getLogger(__name__)


class RenkanGetPut(View):
    
    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(RenkanGetPut, self).dispatch(*args, **kwargs)
    
    def get(self, request):
        #file_path = settings.JSON_TEST_PATH
        #content = open(file_path,"r")
        
        now = datetime.now().strftime("%Y-%m-%d %H:%M")
        
        content = {
          "id": unicode(uuid.uuid1()),
          "title": "Renkan généré " + now,
          "description": "(empty description)",
          "created": now,
          "updated": now,
          "nodes": [],
          "edges": [],
          "views": [],
          "users": [],
        }
        
        # 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) )
        
        # 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)
        
        # Prepare Node placer :
        np = LineNodePlacer()
        np.init({"tags": len(all_tags), "datasheet":len(filter_output["contents"])})
        
        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": None,
              "size": 0,
              "project_id": project_id,
              #"created_by": "roster_user-84fe909f-ba37-48e6-a25f-9d2f129a95b7"
            })
        
        for c in filter_output["contents"]  :
            content["nodes"].append({
              "id": unicode(uuid.uuid1()),
              "title": c["title"],
              "description": c["description"],
              "uri": c["url"],
              "position": np.get_place("datasheet"),
              "image": None,
              "size": 0,
              "project_id": project_id,
              #"created_by": "roster_user-84fe909f-ba37-48e6-a25f-9d2f129a95b7"
            })
        
        
        
        return HttpResponse(json.dumps(content), content_type="application/json")
    
    
    def put(self, request):
        
        return HttpResponse("OK")
        
    