# -*- coding:utf-8 -*-
"""
Function: get_os_firmware.py moudle. This moudle mainly involves the
Obtaining In-Band Upgradeable Firmware function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2017-2020
"""
from scripts.common_function import TIMEOUT_THIRTY


def getosfirmware_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Obtaining In-Band Upgradeable Firmware
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('getosfw',
                                   help='get OS firmware that can be upgraded')
    parser_dict['getosfw'] = sub_parser

    return 'getosfw'


def getosfirmware(client, _):
    """
    Function Description:Obtaining In-Band Upgradeable Firmware
    Parameter:client refishClient: class object
    """
    # Obtain upgradeable firmware collection resources.
    url = "/redfish/v1/Sms/1/UpdateService/FirmwareInventory"
    resp = client.get_resource(url, timeout=TIMEOUT_THIRTY)

    if resp is None:
        return None
    if resp['status_code'] == 404:
        print('Failure: failed to obtain iBMA information')
    elif resp['status_code'] == 200:
        print_result(client, resp)

    return resp


def print_result(client, resp):
    """
    Function Description:print result
    Parameter:client refishClient: class object
    resp dict:redfish interface value
    """
    tmp_count = 0
    firmware_count = len(resp['resource'].get('Members', {}))
    if firmware_count > 0:
        print('-' * 40)
        while tmp_count < firmware_count:
            for key in resp['resource'].get('Members', {})[tmp_count]:
                firmware_url = resp['resource'].get('Members', {})[tmp_count].get(key, "")

                client.get_os_firmware_or_driver(firmware_url)
                tmp_count += 1
    else:
        print('There is no firmware to be upgraded on the OS')
