from ansible.errors import AnsibleFilterError, AnsibleFilterTypeError
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_native


def hex_to_rgb(hex):
    """
    Convert a HEX color string to a list of RGB values.

    Example: '#2e3440' -> [46, 52, 64].
    """
    if isinstance(hex, string_types):
        if len(hex) == 7 and hex[0] == '#':
            try:
                red = int(hex[1:3], base=16)
                green = int(hex[3:5], base=16)
                blue = int(hex[5:7], base=16)

                return [red, green, blue]
            except Exception as e:
                raise AnsibleFilterError("hex_to_rgb - %s" % to_native(e),
                                         orig_exc=e)
        else:
            raise AnsibleFilterError(
                "hex_to_rgb expects 7-character string started with '#', got %s instead."
                % hex)
    else:
        raise AnsibleFilterTypeError(
            "|hex_to_rgb expects string, got %s instead." % type(hex))


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

    def filters(self):
        return {'hex_to_rgb': hex_to_rgb}
