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

@author: tc
'''
from datetime import datetime
from django.core.urlresolvers import reverse
from django.http.response import HttpResponse, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from renkanmanager.models import Renkan
from renkanmanager.utils import LineNodePlacer, renkan_copier, renkan_deleter
import uuid
import json

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):
        
        # 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")
        
        return HttpResponseBadRequest("An error occurred while getting renkan.")
    
    
    def put(self, request):
        
        rk_id = request.GET.get("rk_id", "")
        #data = json.loads(request.body)
        #logger.debug(data["edges"])
        #logger.debug(data["nodes"])
        #logger.debug(request.user.is_authenticated())
        #logger.debug(request.user.is_anonymous())
        if rk_id!="":
            rk = get_object_or_404(Renkan, rk_id=rk_id)
            if rk.owner!=request.user:
                return HttpResponseBadRequest("You are not allowed to edit this renkan")
            rk.content = request.body
            data = json.loads(request.body)
            if "title" in data:
                rk.title = data["title"]
            rk.save()
            return HttpResponse("SAVED")
            
        return HttpResponse("NOT SAVED")





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





class RenkanDelete(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('home'))
    