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


def exportcsr_init(parser, parser_dict):
    """
    Function Description:initializing the Command for Exporting a CSR File
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('exportcsr',
                                   help='export certificate signing request')

    sub_parser.add_argument('-C', dest='Content',
                            type=str,
                            required=False,
                            default=None,
                            help='path of the CSR file of the SSL'
                                 ' certificate. On a local file'
                                 ' server, the CSR file 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 export:Folder/File name.\n\r')

    image_uri = {common_function.REQUIRED_FLAG: False,
                 common_function.HELP_INFO: 'path of the CSR file of the SSL'
                                            ' certificate. On a local file'
                                            ' server, the CSR file 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['exportcsr'] = sub_parser

    return 'exportcsr'


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

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

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

    else:
        message = (ex_resp['resource']['Messages']['Message']).lower()
        print('Failure: ' + message[:-1])


def _respparse(resp, client, slotid, file_path, args):
    """
    Function Description: parse response code and body
    Parameter:resp dict:redfish interface value
    client refishClient: class object
    slotid str:manager id
    file_path str:export local path
    args object:CLI command
    """
    if resp['status_code'] == common_function.REDFISH_STATUS_CODE_200:
        if args.file is not None:
            common_function.export_local_path(client, slotid, file_path, args)
        print('Success: successfully completed request\r')
    else:
        print_err_result(resp)


def print_err_result(resp):
    """
    Function Description: print error result
    Parameter:resp dict:redfish interface value
    """
    messageid = resp['message']['error']['@Message.ExtendedInfo'][0].get(
        'MessageId')
    if 'Format' in messageid:
        print('Failure: export failed due to invalid path')
    else:
        message = (
            resp['message']['error']['@Message.ExtendedInfo'][0].get(
                'Message')).lower()
        print('Failure: ' + message[:-1])


def exportcsr(client, args):
    """
    Function Description: export CSR
    Parameter:client refishClient:class object
    args object:CLI command
    """
    file_path = get_file_path(args)
    payload = {"Type": "URI", "Content": file_path}

    slotid = client.get_slotid()
    if slotid is None:
        return None

    url = "/redfish/v1/Managers/%s/SecurityService" % slotid + \
          "/HttpsCert/Actions/HttpsCert.ExportCSR"
    resp = client.create_resource(url, payload)

    if resp is None:
        return None

    if resp['status_code'] == common_function.REDFISH_STATUS_CODE_202:

        resp_task = client.print_task_prog(resp, flag="exportcsr")
        if resp_task is None:
            return None
        if resp_task == 'Exception':
            _resptaskparse(resp, client)
            sys.exit(common_function.UREST_STATUS_CODE_144)
        if resp_task == 'Completed':
            if args.file is not None:
                common_function.export_local_path(client, slotid, file_path,
                                                  args)
            print('Success: successfully completed request\n')
    else:
        _respparse(resp, client, slotid, file_path, args)
    return resp


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

    if file_path is None:
        sys.exit(common_function.UREST_STATUS_CODE_2)

    return file_path


def check_parameter(_, 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 CSR file of the SSL'
              ' certificate. On a local file'
              ' server, the CSR file 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
