# -*- coding: utf-8 -*-
'''
Created on Mar 13, 2012

@author: ymh and tc
'''
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.http.response import Http404
from django.shortcuts import get_object_or_404
from django.utils.encoding import smart_str
from renkanmanager.models import Renkan
import md5
import re
import uuid

import logging
logger = logging.getLogger(__name__)


def fix_cache_key(key):
    cache_key = re.sub(r'\s+', '-', key)
    cache_key = smart_str(cache_key)
    if len(cache_key) > (250-(2+len(cache.key_prefix)+len(str(cache.version)))-33):
        cache_key = cache_key[:(250-(2+len(cache.key_prefix)+len(str(cache.version)))-33)] + '-' + md5.new(cache_key).hexdigest()
    return cache_key



class NodePlacer():
    
    cat_nb_nodes = {}
    
    def init(self, cat_nb_nodes_initial):
        raise NotImplementedError( "Should have implemented get_place" )
    
    def get_place(self, category):
        if not category or category not in self.cat_nb_nodes:
            raise Http404
        return self.cat_nb_nodes[category].pop(0)



class LineNodePlacer(NodePlacer):
    
    max_length = 0
    
    def init(self, cat_nb_nodes_initial):
        for c in cat_nb_nodes_initial:
            nb = cat_nb_nodes_initial[c]
            if isinstance(cat_nb_nodes_initial[c], tuple):
                _, nb = nb
            self.max_length = nb if nb > self.max_length else self.max_length
        for i_cat,c in enumerate(cat_nb_nodes_initial):
            self.cat_nb_nodes[c] = []
            order = i_cat
            nb = cat_nb_nodes_initial[c]
            if isinstance(cat_nb_nodes_initial[c], tuple):
                order, nb = nb
            offset = float(self.max_length - nb) / 2
            for i in xrange(nb):
                self.cat_nb_nodes[c].append({ "x": order*300, "y": 100*(i+offset) })
        #logger.debug(self.cat_nb_nodes)



class CircleNodePlacer(NodePlacer):
    #TODO: Does not work. Meant to be a real circle placer
    def init(self, cat_nb_nodes_initial):
        for c in cat_nb_nodes_initial:
            self.max_length = cat_nb_nodes_initial[c] if cat_nb_nodes_initial[c] > self.max_length else self.max_length
        for i_cat,c in enumerate(cat_nb_nodes_initial):
            self.cat_nb_nodes[c] = []
            offset = float(self.max_length - cat_nb_nodes_initial[c]) / 2
            for i in xrange(cat_nb_nodes_initial[c]):
                self.cat_nb_nodes[c].append({ "x": i_cat*400, "y": 200*(i+offset) })
        #logger.debug(self.cat_nb_nodes)



def renkan_copier(user, old_rk_id):
    old_rk = get_object_or_404(Renkan, rk_id=old_rk_id)
    rk = Renkan()
    rk.rk_id = unicode(uuid.uuid1())
    rk.owner = user
    rk.content = old_rk.content
    #TODO : update title and uuid in the content's json data
    rk.title = old_rk.title + " (copy)"
    rk.save()
    return rk



def renkan_deleter(user, rk_id):
    rk = get_object_or_404(Renkan, rk_id=rk_id)
    if rk.owner==user:
        rk.delete()
    else:
        raise ValidationError("You are not allowed to remove this renkan")



