# -*- coding:utf-8 -*-
"""
Function: get_pcie_devices.py. This file mainly involves the
Querying PCIe 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
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 getpciedevices_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Querying PCIe Information
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('getpciedevices', help='''get PCIe information''')
    parser_dict['getpciedevices'] = sub_parser
    return 'getpciedevices'


def getpciedevices(client, _):
    """
    Function Description:Querying PCIe Information
    Parameter:client refishClient: class object
    """
    slotid = client.get_slotid()
    if slotid is None:
        return UREST_STATUS_CODE_148
    pcie_url = "/redfish/v1/Chassis/%s/PCIeDevices" % slotid
    pcie_resp = client.get_resource(pcie_url)
    if pcie_resp is None:
        return UREST_STATUS_CODE_148
    if pcie_resp.get("status_code") == REDFISH_STATUS_CODE_404:
        print('Failure: resource was not found')
    if pcie_resp.get("status_code") != REDFISH_STATUS_CODE_200:
        print('Failure: get PCIeDevices error')
        return pcie_resp
    devices = []
    for member in pcie_resp.get(RESOURCE).get("Members"):
        device_url = member.get("@odata.id")
        device_resp = client.get_resource(device_url)
        if device_resp is None:
            continue
        if device_resp.get("status_code") == REDFISH_STATUS_CODE_200:
            devices.append(device_resp.get(RESOURCE))
    print_result(devices)
    return pcie_resp


def print_result(devices):
    """
    Function Description:print result
    Parameter: devices: redfish interface Value
    """
    if len(devices) == 0:
        print("no data available for the resource")
        return
    print("-" * 50)
    for device in devices:
        if device.get("Oem").get(COMMON_KEY_XFUSION) is not None:
            device_info = device.get("Oem").get(COMMON_KEY_XFUSION)
        else:
            device_info = device.get("Oem").get(COMMON_KEY)
        for key in device_info:
            print(FORMAT % (key, device_info.get(key, None)))
        print('\n[Status]')
        status = device.get("Status")
        for key in status:
            print(FORMAT % (key, status.get(key, None)))
        print("-" * 50)
