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


def getsshpublickey_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Querying an SSH Public Key
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('getsslpubkey',
                                   help='''get SSH public key''')
    parser_dict['getsslpubkey'] = sub_parser

    return 'getsslpubkey'


def getsshpublickey(client, _):
    """
    Function Description:Querying an SSH Public Key
    Parameter:client refishClient: class object
    """
    proplength = 20
    m_format = '%-*s:%-*s'
    data = False

    url = "/redfish/v1/AccountService/Accounts"
    resp = client.get_resource(url)

    if resp is None or resp['status_code'] != REDFISH_STATUS_CODE_200:
        return None

    members = resp['resource']["Members"]
    length = len(members)

    for i in range(0, length):
        urltemp = members[i]['@odata.id']
        resptemp = client.get_resource(urltemp)

        if resptemp.get('status_code') != REDFISH_STATUS_CODE_200:
            continue
        userid = resptemp['resource'].get("Id", '')
        username = resptemp['resource'].get("UserName", '')
        vendor_info = common_function.get_vendor_value(resptemp)
        sshkey = vendor_info.get("SSHPublicKeyHash", '')

        if sshkey is None:
            continue

        if data is False:
            print('[SSHPublicKeyHash]')
            data = True

        print('-' * 60)
        print(m_format % (proplength, 'UserId', proplength, userid))
        print(m_format % (proplength, 'UserName', proplength, username))
        print(m_format % (proplength, 'SSHPublicKeyHash', proplength, sshkey))

    if data is False:
        print("no data available for the resource")
    else:
        print('-' * 60)

    return resp
