# -*- coding:utf-8 -*-
"""
Function: get_fru.py. This file mainly involves the
Querying FRU 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

FORMAT = '%-30s: %s'


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


def getfru(client, _):
    """
    Function Description:Querying FRU Information
    Parameter:client refishClient: class object
    """
    slotid = client.get_slotid()
    if slotid is None:
        return UREST_STATUS_CODE_148
    fru_url = "/redfish/v1/Chassis/%s/Boards/chassisMainboard" % slotid
    fru_resp = client.get_resource(fru_url)
    if fru_resp is None:
        return UREST_STATUS_CODE_148
    if fru_resp.get("status_code") == REDFISH_STATUS_CODE_404:
        print('Failure: resource was not found')
        return fru_resp
    product_manufacturer_url = "/redfish/v1/Systems/%s" % slotid
    product_manufacturer_resp = client.get_resource(product_manufacturer_url)
    result = {}
    if fru_resp.get("status_code") == REDFISH_STATUS_CODE_200:
        resource = fru_resp.get(RESOURCE)
        result["Board Mfg Date"] = resource.get("ManufactureDate", None)
        result["Board Mfg"] = resource.get("Manufacturer", None)
        result["Board Product"] = resource.get("BoardName", None)
        result["Board Serial"] = resource.get("SerialNumber", None)
        result["Product Name"] = resource.get("ProductName", None)
    if product_manufacturer_resp is not None \
            and product_manufacturer_resp.get("status_code") == REDFISH_STATUS_CODE_200:
        result["Product Manufacturer"] = product_manufacturer_resp.get(RESOURCE)\
            .get("Manufacturer", None)
    print_result(result)
    return fru_resp


def print_result(result):
    """
    Function Description:print result
    Parameter: resp: redfish interface Value
    """
    print("-" * 50)
    print(FORMAT % ("Board Mfg Date", result.get("Board Mfg Date")))
    print(FORMAT % ("Board Mfg", result.get("Board Mfg")))
    print(FORMAT % ("Board Product", result.get("Board Product")))
    print(FORMAT % ("Board Serial", result.get("Board Serial")))
    print(FORMAT % ("Product Manufacturer", result.get("Product Manufacturer")))
    print(FORMAT % ("Product Name", result.get("Product Name")))
    print("-" * 50)
