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


def uploadntpgroupkey_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Importing an NTP Security Public Key
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('importntpkey',
                                   help='import network time protocol secure '
                                        'group key')

    sub_parser.add_argument('-c', dest='content',
                            type=str, required=False,
                            default=None,
                            help='path of the NTP security public'
                                 ' key file. On a local file server'
                                 ', the key 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 '
                                 'import:Folder/File name.')

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

    return 'importntpkey'


def get_file_path(args, client):
    """
    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.import_file_path(client, 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 get_taskinfo(client, task_uri):
    """
    Function Description:Query the task status
    Parameter:client refishClient:class object
    task_uri str:task url
    Return Value:get_resp dict:result of the redfish interface
    """
    get_resp = client.get_resource(task_uri)
    if get_resp is None:
        return get_resp
    if get_resp['status_code'] != common_function.REDFISH_STATUS_CODE_200:
        return get_resp
    # Query the progress
    get_resp = client.print_task_prog(get_resp)
    if get_resp == 'Exception':
        print('Failure: failed to uplocad the NTP group key, '
              'ensure that the path is valid')
        sys.exit(144)

    return get_resp


def get_response(payload, client, slotid):
    """
    Function Description:get response
    Parameter:payload dict:redfish Parameter
    client refishClient:class object
    slotid str:manager id
    Return Value:patch_resp dict:result of the redfish interface
    """
    url = ("/redfish/v1/Managers/" +
           "%s/NtpService/Actions/NtpService.ImportNtpKey") % slotid
    patch_resp = client.create_resource(url, payload)
    if patch_resp is None:
        return patch_resp
    if patch_resp['status_code'] == common_function.REDFISH_STATUS_CODE_200:
        print('Success: successfully completed request')
    elif patch_resp['status_code'] == common_function.REDFISH_STATUS_CODE_400:
        print('Failure: failed to uplocad the NTP group key, ensure that '
              'the path is valid')
    elif patch_resp['status_code'] == common_function.REDFISH_STATUS_CODE_202:
        task_uri = patch_resp['resource']['error']['@Message.ExtendedInfo'][0][
            '@odata.id']
        patch_resp = get_taskinfo(client, task_uri)
    elif patch_resp['status_code'] == common_function.REDFISH_STATUS_CODE_404:
        print('Failure: resource was not found')

    return patch_resp


def uploadntpgroupkey(client, args):
    """
    Function Description:Importing an NTP Security Public Key
    Parameter:client refishClient:class object
    args object:CLI command
    Return Value:resp dict:result of the redfish interface
    """
    payload = {}
    payload['Type'] = 'URI'
    file_path = get_file_path(args, client)
    payload['Content'] = file_path
    slotid = client.get_slotid()
    if slotid is None:
        return None
    resp = get_response(payload, client, slotid)

    return resp


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 NTP security public'
              ' key file. On a local file server'
              ', the key 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
