from datetime import datetime


def format_event(event, fmt, datefmt=None):
    """Format the received event using the provided format.

    :param theia.model.Event event: the event to format.
    :param str fmt: the format string. This is compatibile with :func:`str.format`.
    :param str datefmt: alternative date format for formatiig the event timestamp.
        The format must be compatible with :func:`datetime.strftime`

    :returns: the formatted event as string.
    """
    data = {
        "id": event.id,
        "tags": ",".join(event.tags),
        "source": event.source,
        "content": event.content
    }
    if datefmt:
        try:
            event_time = datetime.fromtimestamp(event.timestamp)
            data['timestamp'] = event_time.strftime(datefmt)
        except ValueError:
            data['timestamp'] = event.timestamp
    else:
        data["timestamp"] = event.timestamp

    return fmt.format(**data)