# -*- coding:utf-8 -*-
"""
Function: get_fan.py moudle. This moudle mainly involves the
Querying Fan Information function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2017-2020
"""
from scripts.common_function import REDFISH_STATUS_CODE_200
from scripts.common_function import REDFISH_STATUS_CODE_404
from scripts import common_function

FAN_FORMAT = '%-30s: %s'


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

    return 'getfan'


def getfan(client, _):
    """
    Function Description:Querying Fan Information
    Parameter:client refishClient: class object
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None
    url = "/redfish/v1/Chassis/%s/Thermal" % slotid
    resp = client.get_resource(url)
    if resp is None:
        return None
    if resp['status_code'] == REDFISH_STATUS_CODE_200:
        print_result(resp)
    elif resp['status_code'] == REDFISH_STATUS_CODE_404:
        print('Failure: resource was not found')
    return resp


def print_result(resp):
    """
    Function Description:print result
    Parameter:resp dict: redfish interface Value
    """
    print("-" * 50)
    if resp['resource'].get("Oem", None) is not None:
        oem_fan = common_function.get_vendor_value(resp)
        for oem_key in oem_fan:
            print(FAN_FORMAT % (oem_key, oem_fan[oem_key]))
    fan = resp['resource']['Fans']
    fan_len = len(fan)
    print("-" * 50)
    idx = 0
    while idx < fan_len:
        fan_info = fan[idx]
        print_fan(fan_info)
        idx += 1


def print_fan(fan_info):
    """
    Function Description:Displays information about a single fan.
    Parameter:fan_info dict: redfish interface Value
    """
    print(FAN_FORMAT % ("MemberId",
                        fan_info.get("MemberId", None)))
    print(FAN_FORMAT % ("Name", fan_info.get("Name", None)))
    if fan_info.get("Oem", None) is not None:
        print(FAN_FORMAT %
              ("Position",
               fan_info["Oem"][common_function.COMMON_KEY].get("Position", None)))
    for key in fan_info:
        if key in ["@odata.id", "MemberId", "Status", "Name", "Oem"]:
            continue
        print(FAN_FORMAT % (key, fan_info.get(key, None)))
    print('\n[Status]')
    if fan_info.get('Status', None) is not None:
        for status_key in fan_info['Status']:
            print(FAN_FORMAT % (status_key,
                                fan_info['Status'][status_key]))
    print("-" * 50)
