from django import template
from django.utils.http import urlencode
from pprint import pprint

register = template.Library()


@register.filter
def to_label(value):
    value = value.replace('_', ' ')
    return value.title()

@register.filter
def config_cur(test_name):
    import urllib.parse
    return urllib.parse.quote_plus(f"/API/REST/Test/v1/ConfigCur?sections=all&test_type_name={test_name}&size=0")


@register.filter
def kv(obj, value):
    pprint("--- kv ---")
    pprint(obj)
    pprint(value)
    return obj[value]


@register.simple_tag
def test_value(obj, sla, service_name):
    pprint("-- test-value --")
    pprint(f"{sla} , {service_name}")
    try:
        for r in obj[sla]['result']:
            if r['service_instance_name'] == service_name:
                return r
        return None
    except:
        return None


@register.simple_tag
def service_value(obj, sla, service_name):

    try:
        for r in obj[sla]:
            if r['ids']['service_name'] == service_name:
                return r
        return None
    except:
        return None



@register.filter
def true_length(obj):
    t = [o for o in obj if o['required'] == True]
    return len(t)

@register.filter
def true_value(obj):
    try:
        t = [(o['name'], o['value']) for o in obj if o['required'] == True]
        return t
    except:
        return []
