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


def importsshpublickey_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Importing an SSH Public Key
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('importsshpubkey',
                                   help='''import SSH public key''')

    sub_parser.add_argument('-I', dest='userid',
                            required=False,
                            help='''user ID''')

    sub_parser.add_argument('-C', dest='Content',
                            type=str,
                            required=False,
                            default=None,
                            help='path of the SSH public key. On a'
                                 ' local file server, the key 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.\n\r')

    image_uri = {common_function.REQUIRED_FLAG: False,
                 common_function.HELP_INFO: 'path of the SSH public key. On a'
                                            ' local file server, the key 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['importsshpubkey'] = sub_parser

    return 'importsshpubkey'


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']

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

    if ssh_resp['status_code'] != common_function.REDFISH_STATUS_CODE_200:
        message = (ssh_resp['message']['error']['@Message.ExtendedInfo'][0][
            'Message']).lower()
        print('Failure: ' + message[:-1])
    else:
        message = (ssh_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')
    elif resp['status_code'] == common_function.REDFISH_STATUS_CODE_404:
        print('Failure: The user ID does not exist\r')
    else:
        msgid = resp['message']['error']['@Message.ExtendedInfo'][0][
            'MessageId']
        if 'Format' in msgid:
            print('Failure: import failed due to invalid path')
        else:
            message = (
                resp['message']['error']['@Message.ExtendedInfo'][0].get(
                    'Message')).lower()
            print('Failure: ' + message[:-1])


def importsshpublickey(client, args):
    """
    Function Description:Importing an SSH Public Key
    Parameter:client refishClient: class object
    args object:CLI command
    """
    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}

    url = "/redfish/v1/AccountService/Accounts/%s/Oem/%s/" \
          "Actions/Account.ImportSSHPublicKey" % (args.userid,
                                                  common_function.COMMON_KEY)
    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)
        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(_, 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 SSH public key. On a'
              ' local file server, the key 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
