from ansible.errors import AnsibleFilterTypeError
from ansible.module_utils.six import string_types, integer_types


# Ansible's "quote" filter is only applied to shell module

def quote_single(str):
    """
    Quote a string with single quote.

    Example: a string -> 'a string'
    """
    if isinstance(str, string_types):
        return "'" + str + "'"
    else:
        raise AnsibleFilterTypeError(
            "|quote_single expects string, got %s instead." % type(str))

def quote_double(str):
    """
    Quote a string with double quote.

    Example: a string -> "a string"
    """
    if isinstance(str, string_types):
        return '"' + str + '"'
    else:
        raise AnsibleFilterTypeError(
            "|quote_double expects string, got %s instead." % type(str))

def random_hex(num):
    """
    Generate a random hex number within the range [0, num)

    Example: random_hex(2**16 - 1) = 446c
    """
    if isinstance(num, integer_types):
        import random
        return '{:x}'.format(random.randint(0, num))
    else:
        raise AnsibleFilterTypeError(
            "|random_hex expects integer, got %s instead." % type(num))

class FilterModule(object):
    """Custom Ansible jinja2 filters for sysconfig playbook."""

    def filters(self):
        return {'quote_single': quote_single, 'quote_double': quote_double, 'random_hex': random_hex}
