import re
import textwrap


def format_policy_listing(data):
    """Formats a list of policies into human readable format

    Args:
        data (list): A list of policies

    Returns:
        The formated string
    """

    out = ""
    i = 1
    for p in data:
        # Shorten to max chars, remove linebreaks
        name = re.sub(r'[\n\r]', ' ',
                      p.name[:22] + '..'
                      if len(p.name) > 24
                      else p.name)
        # Shorten to 54 chars max, remove linebreaks
        desc = re.sub(r'[\n\r]', ' ',
                      p.description[:52] + '..'
                      if len(p.description) > 54
                      else p.description)
        time = f"{p.time_created:%Y-%m-%d %H:%M}" \
            if p.time_created is not None else ""
        statements = ""
        for s in p.statements:
            statements += textwrap.fill(
                re.sub(r'[\n\r]', ' ', s), width=93,
                initial_indent=' ' * 5 + '- ',
                subsequent_indent=' ' * 7) + "\n"

        out += (f"{i:>4} {name:24} {desc:54} {time:16} {p.lifecycle_state}\n"
                f"{statements}")
        i += 1
    return out