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

@author: ymh and tc
'''
from django.core.cache import cache
from django.http.response import Http404
from django.utils.encoding import smart_str
import md5
import re

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)
        
                
    
        
        