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


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

    return 'getdriver'


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

    if resp is None:
        return None
    if resp['status_code'] == REDFISH_STATUS_CODE_404:
        print('Failure: failed to obtain iBMA information')
    elif resp['status_code'] == REDFISH_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 result
    """
    tmp_count = 0
    driver_count = len(resp['resource'].get('Members', {}))
    print('-' * 40)
    if driver_count > 0:
        while tmp_count < driver_count:
            for key in resp['resource']['Members'][tmp_count]:
                driver_url = resp['resource']['Members'][tmp_count].get(key, '')
                client.get_os_firmware_or_driver(driver_url)
                tmp_count += 1
    else:
        print('There is no driver to be upgraded on the OS')
