# -*- coding:utf-8 -*-
"""
Function: get_twofactor_cert.py moudle. This moudle mainly involves the
Querying a Dual-Factor Certificate 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 gettwofactorcert_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Querying a Dual-Factor Certificate
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('get2factorcert',
                                   help='''get two factor certificate''')
    sub_parser.add_argument('-T', dest='Type',
                            required=True,
                            choices={'root', 'client'},
                            help='''two factor certificate type''')

    parser_dict['get2factorcert'] = sub_parser

    return 'get2factorcert'


def _printcertificateinformation(certificateinformation):
    """
    Function Description:print client certificate information
    Parameter:certificateinformation dict: redfish interface Value
    """
    proplength = 13
    fmt = '%-*s:%-*s'

    for k in certificateinformation:
        print(fmt % (proplength, k, proplength, certificateinformation[k]))


def _gettwofactorcerroottificate(client):
    """
    Function Description:print root certificate information
    Parameter:client refishClient: class object
    """
    url = "/redfish/v1/AccountService"

    resp = client.get_resource(url)

    if resp is None or resp['status_code'] == REDFISH_STATUS_CODE_200:
        resp_inner_dic = common_function.get_vendor_value(resp)
        rootcertificate = resp_inner_dic["TwoFactorAuthenticationInformation"][
            "RootCertificate"]

        len_cer = len(rootcertificate)
        if len_cer == 0:
            print("no data available for the resource")
            return None

        print('[RootCertificate]')
        for i in range(0, len_cer):
            print('-' * 50)
            _printcertificateinformation(rootcertificate[i])

        print('-' * 50)

    return resp


def _gettwofactorcerclienttificate(client):
    """
    Function Description:get two factor certificate
    Parameter:client refishClient: class object
    """
    proplength = 13
    m_format = '%-*s:%-*s'

    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)

    data = False

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

        if resp['status_code'] != REDFISH_STATUS_CODE_200:
            continue
        userid = resptemp['resource'].get("Id", "")
        username = resptemp['resource'].get("UserName", "")
        vendor_dict = common_function.get_vendor_value(resptemp)
        cert = vendor_dict["MutualAuthClientCert"]

        if cert is None:
            continue

        if not data:
            print("[MutualAuthClientCert]")
            data = True

        print('-' * 50)
        print(m_format % (proplength, 'UserId', proplength, userid))
        print(m_format % (proplength, 'UserName', proplength, username))

        _printcertificateinformation(cert)

    if not data:
        print("no data available for the resource")
        return resp
    print('-' * 50)

    return resp


def gettwofactorcert(client, args):
    """
    Function Description:Querying a Dual-Factor Certificate
    Parameter:client refishClient: class object
    args object:CLI command
    """
    if args.Type == 'root':
        resp = _gettwofactorcerroottificate(client)
    else:
        resp = _gettwofactorcerclienttificate(client)

    return resp
