# -*- coding: utf-8 -*-
"""
Function: get_ldap_info.py moudle. This moudle mainly involves the
Querying LDAP Information function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2017-2020
"""

LEN = 32
MFORMAT = '%-*s:%-*s'


def getldapinfo_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Querying LDAP Information
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('getldap',
                                   help='''get LDAP information''')
    sub_parser.add_argument('-I', dest='ID',
                            type=str, required=False,
                            help='''LDAP Controller ID''',
                            choices=['1', '2', '3', '4', '5', '6'])
    parser_dict['getldap'] = sub_parser

    return 'getldap'


def _printcertificateinformation(certinfo):
    """
    Function Description:print certificate information
    Parameter:certinfo dict: redfish interface Value
    """
    for k in certinfo:
        print(MFORMAT % (LEN, k, LEN, certinfo[k]))


def _joingrouprule(arrary):
    """
    Function Description:join group rule
    Parameter:arrary list: redfish interface Value
    """
    if arrary is None:
        return None
    length = len(arrary)

    if length == 0:
        return None
    rvalue = "Rule%s" % arrary[0]['@odata.id'].split(r'/')[8]

    for i in range(1, length):
        rvalue = "%s,Rule%s" % (rvalue, arrary[i]['@odata.id'].split(r'/')[8])

    return rvalue


def _joingroupinterface(arrary):
    """
    Function Description:join group interface
    Parameter:arrary list: redfish interface Value
    """
    if arrary is None:
        return None
    length = len(arrary)

    if length == 0:
        return None
    rvalue = arrary[0]

    for i in range(1, length):
        rvalue = "%s,%s" % (rvalue, arrary[i])

    return rvalue


def _printgroupinfo(ldapgroups):
    """
    Function Description:print group info
    Parameter:ldapgroups list: redfish interface Value
    """
    print('[LdapGroups]')
    role_dict = {"Common User": "CommonUser", "Operator": "Operator",
                 "Administrator": "Administrator",
                 "Custom Role 1": "CustomRole1",
                 "Custom Role 2": "CustomRole2",
                 "Custom Role 3": "CustomRole3",
                 "Custom Role 4": "CustomRole4", "No Access": "NoAccess"}
    length = len(ldapgroups)
    for i in range(0, length):
        memberid = ldapgroups[i].get('MemberId', '')
        gname = ldapgroups[i].get('GroupName', '')
        gdomain = ldapgroups[i].get('GroupDomain', '')
        grole = role_dict.get(ldapgroups[i].get('GroupRole', {}), "CommonUser")
        grulet = ldapgroups[i].get('GroupLoginRule', {})
        grule = _joingrouprule(grulet)

        ginterfacet = ldapgroups[i]['GroupLoginInterface']
        ginterface = _joingroupinterface(ginterfacet)

        print('-' * 50)
        print(MFORMAT % (LEN, 'MemberId', LEN, memberid))
        print(MFORMAT % (LEN, 'GroupName', LEN, gname))
        print(MFORMAT % (LEN, 'GroupDomain', LEN, gdomain))
        print(MFORMAT % (LEN, 'GroupRole', LEN, grole))
        print(MFORMAT % (LEN, 'GroupLoginRule', LEN, grule))
        print(MFORMAT % (LEN, 'GroupLoginInterface', LEN, ginterface))
    print('-' * 50)


def _getldapcontroller(client, memberid):
    """
    Function Description:get LDAP controller
    Parameter:  client refishClient: class object
    memberid str:LDAP Controller ID
    """
    urltemp = "/redfish/v1/AccountService/LdapService/LdapControllers/"
    urltemp = urltemp + ("%s" % memberid)

    resptemp = client.get_resource(urltemp)

    if resptemp is None:
        return None

    if resptemp['status_code'] == 200:
        resource = resptemp['resource']

        ldapserveraddress = resource.get('LdapServerAddress', '')
        ldapport = resource.get('LdapPort', '')
        userdomain = resource.get('UserDomain', '')
        certven = resource.get('CertificateVerificationEnabled', '')
        certinfo = resource.get('CertificateInformation', {})
        ldapgroups = resource.get('LdapGroups', {})

        print(MFORMAT % (LEN, 'LdapServerAddress', LEN, ldapserveraddress))
        print(MFORMAT % (LEN, 'LdapPort', LEN, ldapport))
        print(MFORMAT % (LEN, 'UserDomain', LEN, userdomain))
        print(MFORMAT % (LEN, 'CertificateVerificationEnabled', LEN, certven))

        print('')
        print('[CertificateInformation]')
        if certinfo is not None:
            _printcertificateinformation(certinfo)

        print('')
        _printgroupinfo(ldapgroups)

    return resptemp


def _getldapcontrollers(client):
    """
    Function Description:get ldap controllers
    Parameter:  client refishClient: class object
    """
    url = "/redfish/v1/AccountService/LdapService"
    resp = client.get_resource(url)

    if resp is None:
        return None

    if resp['status_code'] == 200:
        ldapenabled = resp['resource']['LdapServiceEnabled']

        print('LdapServiceEnabled: %s' % ldapenabled)
        print('')

    print('[LdapControllers]')

    for i in range(0, 6):

        urltemp = "/redfish/v1/AccountService/LdapService/LdapControllers/"
        urltemp = urltemp + ("%s" % (i + 1))
        resptemp = client.get_resource(urltemp)
        if resptemp is None:
            return None
        if resptemp['status_code'] == 200:
            resource = resptemp['resource']
            memberid = resource.get('Id', '')
            ldapserveraddress = resource.get('LdapServerAddress', '')
            ldapport = resource.get('LdapPort', '')
            userdomain = resource.get('UserDomain', '')
            certven = resource.get('CertificateVerificationEnabled', '')
        else:
            return resptemp

        print('-' * 50)
        print(MFORMAT % (LEN, 'Id', LEN, memberid))
        print(MFORMAT % (LEN, 'LdapServerAddress', LEN, ldapserveraddress))
        print(MFORMAT % (LEN, 'LdapPort', LEN, ldapport))
        print(MFORMAT % (LEN, 'UserDomain', LEN, userdomain))
        print(MFORMAT % (LEN, 'CertificateVerificationEnabled', LEN, certven))
    print('-' * 50)
    return resp


def getldapinfo(client, args):
    """
    Function Description:Querying LDAP Information
    Parameter: client refishClient: class object
    args object:CLI command
    """
    if args.ID is not None:
        resp = _getldapcontroller(client, args.ID)
    else:
        resp = _getldapcontrollers(client)
    return resp
