# -*- coding:utf-8 -*-
"""
Function: get_ssl_cert.py moudle. This moudle mainly involves the
 querying an SSL Certificate function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2020-2021
"""


def getsslcert_init(parser, parser_list):
    """
    #=====================================================================
    #   @Description:  get SSL cert init
    #
    #   @Date:
    #=====================================================================
    """
    sub_parser = parser.add_parser('getsslcert',
                                   help='''get SSL certificate''')

    parser_list['getsslcert'] = sub_parser

    return 'getsslcert'


def _printcertificateinformation(certinformation):
    """
    #=====================================================================
    #   @Description:  print certificate information
    #
    #   @Date:
    #=====================================================================
    """
    length = 20
    m_format = '%-*s:%-*s'

    for k in certinformation:
        print(m_format % (length, k, length, certinformation[k]))


def _printintermediatecert(intermediatecert):
    """
    #=====================================================================
    #   @Description:  print intermediate certificate
    #
    #   @Date:
    #=====================================================================
    """
    if len(intermediatecert) == 1:
        _printcertificateinformation(intermediatecert[0])

    elif len(intermediatecert) > 1:
        for cert_info in intermediatecert:
            print('-' * 50)
            _printcertificateinformation(cert_info)
        print('-' * 50)


def getsslcert(client, _):
    """
    #=====================================================================
    #   @Description:  get SSL cert
    #
    #   @Date:
    #=====================================================================
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None

    url = "/redfish/v1/Managers/%s/SecurityService/HttpsCert" % slotid
    resp = client.get_resource(url)

    if resp is None:
        return None
    if resp['status_code'] == 200:
        print_result(resp)

    return resp


def print_result(resp):
    """
    功能描述：打印 请求结果
    参数：resp (dict):redfish 接口返回值
    返回值：None
    异常描述：None
    修改：None
    """
    x509cert = resp['resource'].get("X509CertificateInformation", {})
    if 'ServerCert' in x509cert:
        print('[ServerCert]')
        servercert = x509cert['ServerCert']
        _printcertificateinformation(servercert)
        print('')
    if 'RootCert' in x509cert:
        print('[RootCert]')
        rootcert = x509cert['RootCert']
        _printcertificateinformation(rootcert)
        print('')
    if 'IntermediateCert' in x509cert:
        print('[IntermediateCert]')
        intermediatecert = x509cert['IntermediateCert']
        _printintermediatecert(intermediatecert)
        print('')
