from django.template import Library
from django.core.serializers import serialize
from iconolab.models import AnnotationRevision
from iconolab.serializers import AnnotationRevisionSerializer
from rest_framework.renderers import JSONRenderer

from iconolab import __version__

register = Library()

# {% transform_matrix 230 200 100 100 %}
@register.simple_tag
def transform_matrix(im_width=0, im_height=0, max_x=0, max_y=0):
	try :
		x_ratio = im_width / max_x
		y_ratio = im_height / max_y
		value_list = [x_ratio, 0, 0, y_ratio, 0, 0]
		matrix = ",".join([str(v) for v in value_list])
	except:
		matrix = ""

	return matrix

@register.filter
def clean_path(path):
	result = ""
	if not len(path):
		return result
	else:
		path_infos = path.split(";")
		if len(path_infos) > 0 :
			result = path_infos[0]
	return result


@register.filter
def path_type(path):
	result = ""
	if not len(path):
		return result
	else:
		path_infos = path.split(";")
		if len(path_infos) > 1 :
			result = path_infos[1]

	return result

@register.simple_tag
def version():
	return __version__

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)


@register.filter
def addstr(arg1, arg2):
    """concatenate arg1 & arg2"""
    return str(arg1) + str(arg2)

@register.filter(name='json')
def json_dumps(data):
    if isinstance(data, AnnotationRevision) :
        serializer = AnnotationRevisionSerializer(data)
        return JSONRenderer().render(serializer.data)
    return serialize('json', [data])

@register.simple_tag(takes_context=True)
def container_class(context):
    request = context['request']
    routes = ['image_detail', 'annotation_detail']
    if request.resolver_match.url_name in routes:
        return 'container-fluid'
    return 'container'

@register.assignment_tag(takes_context=True)
def is_bookmarked(context, image):
    request = context['request']
    return image.is_bookmarked_by(request.user)
