# -*- coding: utf-8 -*-
"""
Function: set_ldap_controller.py moudle. This moudle mainly involves the
Setting LDAP Controller Information function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2017-2020
"""
import sys
from scripts import common_function


def setldapcontroller_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Setting LDAP Controller Information
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('setldap',
                                   help='''set LDAP controller information''')

    sub_parser.add_argument('-I', dest='memberid',
                            choices=['1', '2', '3', '4', '5', '6'],
                            required=True,
                            help='''LDAP controller ID''')
    sub_parser.add_argument('-A', dest='address', type=str,
                            required=False,
                            help='''LDAP service address''')
    sub_parser.add_argument('-p', dest='ldapport', type=int,
                            required=False,
                            help='''LDAP port, 1 to 65535''')
    sub_parser.add_argument('-D', dest='domain', type=str,
                            required=False,
                            help='user domain, example: User,DC=company,'
                                 'DC=ibmc,DC=com')
    sub_parser.add_argument('-S', dest='cvenabled', type=str,
                            choices=['True', 'False'], required=False,
                            help='''certificate verification enabled''')
    parser_dict['setldap'] = sub_parser
    return 'setldap'


def print_err_fh(msgs):
    """
    Function Description:Print error information.
    Parameter: msgs dict: redfish interface Value
    """
    if msgs is None:
        return
    for index, value in enumerate(msgs):
        len_msg = len(value['RelatedProperties'])
        if len_msg == 0:
            msg = value['MessageArgs'][1]
        else:
            msg = value['RelatedProperties'][0].replace('#/', '')
        if index == 0:
            print('Failure: invalid property %s value' % msg)
        else:
            print('         invalid property %s value' % msg)


def print_err_th(msgs):
    """
    Function Description:Print error information.
    Parameter: msgs dict: redfish interface Value
    """
    if msgs is None:
        return
    error = 'Failure: some of the settings failed. '
    error = error + 'possible causes include the following:'
    print(error)
    for msg_info in msgs:
        len_msg = len(msg_info['RelatedProperties'])
        if len_msg == 0:
            msg = msg_info['MessageArgs'][1]
        else:
            msg = msg_info['RelatedProperties'][0].replace('#/', '')
        print('         Invalid property %s value' % msg)


def setldapcontroller(client, args):
    """
    Function Description:Setting LDAP Controller Information
    Parameter:client refishClient: class object
    args object:CLI command
    """
    url = "/redfish/v1/AccountService/LdapService/LdapControllers/"
    url = url + "%s" % args.memberid
    resp = client.get_resource(url)
    if resp is None:
        return None
    if resp['status_code'] != common_function.REDFISH_STATUS_CODE_200:
        return resp
    payload = get_payload(args)

    resp = client.set_resource(url, payload)
    if resp.get('status_code') == common_function.REDFISH_STATUS_CODE_200:
        # Some of the settings failed
        if resp['resource'].get('@Message.ExtendedInfo') is not None:
            messages = resp['resource']['@Message.ExtendedInfo']
            print_err_th(messages)
            sys.exit(common_function.UREST_STATUS_CODE_144)
        else:
            print('Success: successfully completed request')
    else:
        if resp.get('status_code') == common_function.REDFISH_STATUS_CODE_400:
            messages = resp['message']['error']['@Message.ExtendedInfo']
            print_err_fh(messages)
    return resp


def check_parameter(parser, args):
    """
    Function Description:check CLI command
    Parameter:args object:CLI command
    parser object:subcommand ArgumentParser object
    """
    if common_function.all_none(args.address, args.ldapport, args.domain,
                                args.cvenabled):
        parser.error('at least one parameter of -A,-p,-D and '
                     '-S must be specified')


def get_payload(args):
    """
    Function Description:init payload
    Parameter:args object:CLI command
    Return Value: payload dict:Redfish interface parameters
    """
    payload = {}
    if args.address is not None:
        payload['LdapServerAddress'] = args.address
    if args.ldapport is not None:
        payload['LdapPort'] = args.ldapport
    if args.domain is not None:
        payload['UserDomain'] = args.domain
    if args.cvenabled is not None:
        if args.cvenabled == 'False':
            payload['CertificateVerificationEnabled'] = False
        else:
            payload['CertificateVerificationEnabled'] = True
    return payload
