# -*- coding:utf-8 -*-
"""
Function: get_sensor.py. This file mainly involves the
Querying Sensor 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 getsensor_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Querying Sensor Information
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('getsensor', help='''get sensor information''')
    parser_dict['getsensor'] = sub_parser
    return 'getsensor'


def getsensor(client, _):
    """
    Function Description:Querying Sensor Information
    Parameter:client refishClient: class object
    """
    slotid = client.get_slotid()
    if slotid is None:
        return UREST_STATUS_CODE_148
    threshold_url = "/redfish/v1/Chassis/%s/ThresholdSensors" % slotid
    threshold_resp = client.get_resource(threshold_url)
    discrete_url = "/redfish/v1/Chassis/%s/DiscreteSensors" % slotid
    discrete_resp = client.get_resource(discrete_url)
    if threshold_resp is None and discrete_resp is None:
        return UREST_STATUS_CODE_148
    if threshold_resp.get("status_code") == REDFISH_STATUS_CODE_404 and \
            discrete_resp.get("status_code") == REDFISH_STATUS_CODE_404:
        print('Failure: resource was not found')
    sensors = []
    if threshold_resp.get("status_code") == REDFISH_STATUS_CODE_200:
        sensors.extend(threshold_resp.get(RESOURCE)["Sensors"])
    if discrete_resp.get("status_code") == REDFISH_STATUS_CODE_200:
        sensors.extend(discrete_resp.get(RESOURCE)["Sensors"])
    print_result(sensors)
    if threshold_resp.get("status_code") == REDFISH_STATUS_CODE_200:
        return threshold_resp
    else:
        return discrete_resp


def print_result(sensors):
    """
    Function Description:print result
    Parameter: sensors: redfish interface Value
    """
    print("-" * 50)
    for sensor in sensors:
        for key in sensor:
            print(FORMAT % (key, sensor.get(key, None)))
        print("-" * 50)
