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


def importldapcert_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Importing an LDAP Certificate
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('importldapcert',
                                   help='''import LDAP certificate''')

    sub_parser.add_argument('-I', dest='ldapID',
                            type=str, required=True,
                            choices=['1', '2', '3', '4', '5', '6'],
                            help='''LDAP controller ID''')

    sub_parser.add_argument('-C', dest='Content',
                            type=str,
                            required=False,
                            default=None,
                            help='path of the LDAP certificate.'
                                 ' On a local file server, the'
                                 ' certificate can be stored only'
                                 ' in the /tmp directory of iBMC,'
                                 ' and the path format is /tmp/file'
                                 ' name. On a remote file server,'
                                 ' the path format is protocol://'
                                 'User name:Password@IP address/'
                                 'Folder/File name. The file '
                                 'transfer protocols include the'
                                 ' following: sftp, https, nfs,' 
                                 ' cifs, scp.')

    sub_parser.add_argument('-F', dest='file', required=False,
                            help='the path of file. Local '
                                 'import:Folder/File name.')

    image_uri = {common_function.REQUIRED_FLAG: False,
                 common_function.HELP_INFO: 'path of the LDAP certificate.'
                                            ' On a local file server, the'
                                            ' certificate can be stored only'
                                            ' in the /tmp directory of iBMC,'
                                            ' and the path format is /tmp/file'
                                            ' name. On a remote file server,'
                                            ' the path format is server'
                                            ' IP address/directory/file name.'}
    args_pro = {common_function.REQUIRED_FLAG: False}
    args_acc = {common_function.REQUIRED_FLAG: False}
    common_function.unpack_remote_server_path(sub_parser, image_uri,
                                              args_pro, args_acc)

    parser_dict['importldapcert'] = sub_parser

    return 'importldapcert'


def _resptaskparse(resp, client):
    """
    Function Description:parse response code and body
    Parameter:client refishClient: class object
    resp dict: redfish interface Value
    """
    taskid = resp['resource']['@odata.id']

    ldap_resp = client.get_resource(taskid)
    if ldap_resp is None:
        sys.exit(common_function.UREST_STATUS_CODE_127)

    if ldap_resp['status_code'] != common_function.REDFISH_STATUS_CODE_200:
        message = (ldap_resp['message']['error']['@Message.ExtendedInfo'][0][
            'Message']).lower()
        print('Failure: ' + message[:-1])
    else:
        message = (ldap_resp['resource']['Messages']['Message']).lower()
        print('Failure: ' + message[:-1])


def _respparse(resp):
    """
    Function Description: parse response code and body
    Parameter:resp dict: redfish interface Value
    """
    if resp['status_code'] == common_function.REDFISH_STATUS_CODE_200:
        print('Success: successfully completed request\r')
    else:
        messageid = resp['message']['error']['@Message.ExtendedInfo'][0].get(
            'MessageId')
        if 'Format' in messageid:
            print('Failure: import failed due to invalid path')
        else:
            message = (
                resp['message']['error']['@Message.ExtendedInfo'][0].get(
                    'Message')).lower()
            print('Failure: ' + message[:-1])


def importldapcert(client, args):
    """
    Function Description:Importing an LDAP Certificate
    Parameter:client refishClient: class object
    args object:CLI command
    """
    url = "/redfish/v1/AccountService/LdapService/LdapControllers" + \
          "/%s/Actions/HwLdapController.ImportCert" % args.ldapID
    remote_path = get_file_path(args)
    file_dict = {common_function.LOCAL: args.file,
                 common_function.REMOTE: remote_path}
    file_path = common_function.local_or_remote_file_path(file_dict, client)

    payload = {"Type": "URI", "Content": file_path}

    resp = client.create_resource(url, payload)

    if resp is None:
        return None

    if resp.get('status_code') == common_function.REDFISH_STATUS_CODE_202:

        resp_task = client.print_task_prog(resp)
        if resp_task is None:
            return None
        if resp_task == 'Exception':
            _resptaskparse(resp, client)
            sys.exit(common_function.UREST_STATUS_CODE_144)
    else:
        _respparse(resp)

    return resp


def get_file_path(args):
    """
    Function Description: get file path
    Parameter:args object:CLI command
    Return Value: file_path
    """
    if args.Content is not None:
        file_path = args.Content
    else:
        file_path = common_function.splice_remote_server_path(args)
    return file_path


def check_parameter(parser, args):
    """
    Function Description:check CLI command
    Parameter:args object:CLI command
    parser object:subcommand ArgumentParser object
    """
    if (args.imageuri is not None or args.protocol is not None or
            args.accessuser is not None) and args.Content is not None:
        print("Failure: -C contains the information of -i -PRO and -U. you can not use -C and -i -PRO -U both.")
        sys.exit(common_function.UREST_STATUS_CODE_2)
    if args.Content is not None and not (common_function.verify_remote_server_info(args.Content)
             or args.Content.startswith("/tmp")):
        print('Failure: path of the LDAP certificate.'
              ' On a local file server, the'
              ' certificate can be stored only'
              ' in the /tmp directory of iBMC,'
              ' and the path format is /tmp/file'
              ' name. On a remote file server,'
              ' the path format is protocol://'
              'User name:Password@IP address/'
              'Folder/File name. The file '
              'transfer protocols include the'
              ' following: sftp, https, nfs,' 
              ' cifs, scp.')
        sys.exit(common_function.UREST_STATUS_CODE_2)


def is_interactive(args):
    """
    Function Description:check CLI command
    Parameter:args object:CLI command
    parser object:subcommand ArgumentParser object
    """
    if args.Content is not None:
        return False
    return True
