# this filter splits a network into multiple networks of class A, B or
# C, as needed.

from ansible.errors import AnsibleFilterTypeError
import netaddr


def split_net(net):
    try:
        net = netaddr.IPNetwork(net)
    except netaddr.AddrFormatError:
        raise AnsibleFilterTypeError("{} is not a valid network".format(net))

    if net.prefixlen < 8:
        split_into = 8
    elif net.prefixlen < 16:
        split_into = 16
    else:
        split_into = 24
    return ["{}/{}".format(n.ip, n.netmask) for n in net.subnet(split_into)]


class FilterModule(object):
    def filters(self):
        return {
            'split_net': split_net
            }

