# -*- coding:utf-8 -*-
"""
Function: get_sp_filelist.py moudle. This moudle mainly involves the
 querying the Smart Provisioning File List function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2020-2021
"""
FORMAT = '%-5s: %s'


def getspfilelist_init(parser, parser_list):
    """
    #=====================================================================
    #   @Method:  SP query subcommand
    #   @Param:   parser, major command argparser
    #                    parser_list, save subcommand parser list
    #   @Return:
    #   @author:
    #=====================================================================
    """
    sub_parser = parser.add_parser('getspfilelist',
                                   help='get SP service file list information')

    parser_list['getspfilelist'] = sub_parser

    return 'getspfilelist'


def getspfilelist(client, _):
    """
    #=====================================================================
    #   @Method: SP file list Query subcommand processing functions.
    #   @Param:  client, RedfishClient object
    #   @Return:
    #   @author:
    #   @date:  2017-11-14 09:04:14
    #=====================================================================
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None

    url = "/redfish/v1/Managers/%s/SPService" % slotid
    resp = client.get_resource(url)
    if resp is None or resp.get("status_code", None) is None:
        print('no data available for the resource')
        return None

    if resp['status_code'] == 200:
        info = resp.get('resource', None)
        no_data_flag = if_no_data(info)
        if no_data_flag:
            return resp
        show_info(info.get("FileList", None), "FileList")
    elif resp['status_code'] == 404:
        print('Failure: resource was not found')
    elif resp['status_code'] == 500:
        print("Failure: the request failed due to an internal service error")

    return resp


def if_no_data(info):
    """
    功能描述：打印没有可用于该资源的数据
    参数：info (dict):redfish 接口返回值
    返回值：None
    异常描述：None
    修改：None
    """
    if info is None:
        print('no data available for the resource')
        return True
    file_list = info.get("FileList")
    if file_list is None or len(file_list) == 0:
        print('no data available for the resource')
        return True
    return False


def show_info(file_list, key):
    """
    功能描述：打印结果
    参数：file_list (list):文件列表
    key (str):关键字
    返回值：None
    异常描述：None
    修改：None
    """
    print('')
    print('[%s]' % key)
    idx = 0
    list_len = len(file_list)
    while idx < list_len:
        list_info = file_list[idx]
        for f_key in list_info:
            print(FORMAT % (f_key, list_info[f_key]))
        idx += 1
        print('')
