#!/usr/bin/env python
# -*- coding: utf-8 -*-

# EesyLDAP -- Simple LDAP Objects mapper
# By: Benjamin Renard <brenard@easter-eggs.com>
#
# Copyright (C) 2019 Benjamin Renard, Easter-eggs
# https://gitlab.com/brenard/eesyldap
#
# This file is part of EesyLDAP.
#
# EesyLDAP is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# EesyLDAP is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

""" Helpers """

import ldap


def format_modlist(modlist, prefix=None):
    """
    Format modlist as generated by ldap.modlist functions

    :param  modlist:    The modlist to format
    :param  prefix:     Prefix string to add on each output lines (optional)
    """
    assert isinstance(modlist, list), "modlist must be a list as generated by ldap.modlist functions (not %s)" % type(modlist)
    if not modlist:
        return "No change"
    msg = []
    if not prefix:
        prefix = ''
    assert isinstance(prefix, str), "prefix must be a string (not %s)" % type(prefix)
    for (op, attr, val) in modlist:
        if op == ldap.MOD_ADD:  # pylint: disable=no-member
            op = 'ADD'
        elif op == ldap.MOD_DELETE:  # pylint: disable=no-member
            op = 'DELETE'
        elif op == ldap.MOD_REPLACE:  # pylint: disable=no-member
            op = 'REPLACE'
        else:
            op = 'UNKNOWN (=%s)' % op
        if val is None and op == 'DELETE':
            msg.append('%s - %s %s' % (prefix, op, attr))
        else:
            msg.append('%s - %s %s: %s' % (prefix, op, attr, val))
    return '\n'.join(msg)
