# -*- coding:utf-8 -*-
"""
Function: get_disk_bp.py. This file mainly involves the
Querying disk back plane Information function.
Copyright: xFusion Digital Technology Co., Ltd. All Rights Reserved (C) 2022-2022
"""
from scripts.common_function import REDFISH_STATUS_CODE_200, UREST_STATUS_CODE_148, RESOURCE, OEM
from scripts.common_function import REDFISH_STATUS_CODE_404
from scripts.common_function import COMMON_KEY
from scripts.common_function import COMMON_KEY_XFUSION

FORMAT = '%-30s: %s'


def getdiskbp_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Querying disk back plane Information
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('getdiskbp', help='''get disk back plane information''')
    parser_dict['getdiskbp'] = sub_parser
    return 'getdiskbp'


def getdiskbp(client, _):
    """
    Function Description:Querying disk back plane Information
    Parameter:client refishClient: class object
    """
    slotid = client.get_slotid()
    if slotid is None:
        return UREST_STATUS_CODE_148
    boards_url = "/redfish/v1/Chassis/%s/Boards" % slotid
    boards_resp = client.get_resource(boards_url)
    if boards_resp is None:
        return UREST_STATUS_CODE_148
    if boards_resp.get("status_code") == REDFISH_STATUS_CODE_404:
        print('Failure: resource was not found')
    if boards_resp.get("status_code") != REDFISH_STATUS_CODE_200:
        print('Failure: get boards error')
        return boards_resp
    if boards_resp.get(RESOURCE).get(OEM).get(COMMON_KEY_XFUSION) is not None:
        boards = boards_resp.get(RESOURCE).get(OEM).get(COMMON_KEY_XFUSION)
    else:
        boards = boards_resp.get(RESOURCE).get(OEM).get(COMMON_KEY)
    diskbps = []
    for link in boards.get("Boards", {}).get("DiskBackplane", {}).get("Links", {}):
        diskbp_url = link.get("@odata.id")
        diskbp_resp = client.get_resource(diskbp_url)
        if diskbp_resp is None:
            continue
        if diskbp_resp.get("status_code") == REDFISH_STATUS_CODE_200:
            diskbps.append(diskbp_resp.get(RESOURCE))
    print_result(diskbps)
    return boards_resp


def print_result(diskbps):
    """
    Function Description:print result
    Parameter: diskbps: redfish interface Value
    """
    if len(diskbps) == 0:
        print("no data available for the resource")
        return
    print("-" * 50)
    for diskbp in diskbps:
        for key in diskbp:
            if key in ["@odata.context", "@odata.id", "@odata.type", "Status"]:
                continue
            print(FORMAT % (key, diskbp.get(key, None)))
        print('\n[Status]')
        status = diskbp.get("Status")
        for key in status:
            print(FORMAT % (key, status.get(key, None)))
        print("-" * 50)
