# -*- coding:utf-8 -*-
"""
Function: get_sd_controller.py moudle. This moudle mainly involves the
 querying SD Controller Information function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2020-2021
"""
import sys

from scripts import common_function

PF1 = '{0}{1}'
PF2 = '{0:30}: {1}'


def getsdcontroller_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    querying SD Controller Information.
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    Modify: 2019.4.28 The help information is optimized.
    Return Value: subcommand
    """
    sub_parser = parser.add_parser('getsd',
                                   help='''get SD controller information''')
    parser_dict['getsd'] = sub_parser

    return 'getsd'


def getsdcontroller(client, _):
    """
    #==========================================================================
    #   @Method:  Obtain storage information subcommand processing functions.
    #   @Param:   client, RedfishClient object
                  parser, subcommand argparser.
                  Export error messages when parameters are incorrect.
                  args, parameter list
    #   @Return:
    #   @Date: 2017 07 17
    #==========================================================================
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None
    # If there is only one parameter,
    # information of the specified controller will be queried.
    systems = "/redfish/v1/systems/" + slotid
    # Check whether a storage system exists in the system.
    url = systems + "/Storages"
    resp = client.get_resource(url)
    if resp is None:
        return resp
    if resp['status_code'] != 200:
        if resp['status_code'] == 404:
            print('Failure: resource was not found')
        return resp

    return get_sd_ctrl(resp, client)


def get_sd_ctrl(resp, client):
    """
    #==========================================================================
    #   @Method:  Obtain complete storage information.
    #   @Param:   client, RedfishClient clicnt,
                  slotid: environment slot information
    #   @Return:  resp
    #   @author:
    #==========================================================================
    """
    # No SD storage device exists in the current environment.
    if not resp['resource']['Members']:
        print('Failure: resource was not found')
        sys.exit(148)

    # SD controller information
    storage_array = resp['resource']['Members']
    index = 0
    array_len = len(storage_array)
    flag = False
    while index < array_len:
        # Update controller information.
        url = resp['resource']['Members'][index].get('@odata.id', '')
        if url.find('SDStorage') > 0:
            flag = True
            get_sd_ctrl_info(client, url)
        index += 1
    if not flag:
        print('Failure: resource was not found')
        sys.exit(148)

    return resp


# Obtain controller information.
def get_sd_ctrl_info(client, sdctrl_uri):
    """
    #==========================================================================
    #   @Method:  Obtain the controller.
    #   @Param:   client, RedfishClient object; sd_uri; controller URL
    #   @Return:  resp
    #   @author:
    #==========================================================================
    """
    # Obtain controller information.
    resp = client.get_resource(sdctrl_uri)
    # If no required information is obtained successfully,
    # the returned value is None.
    if resp is None:
        return None
    if resp['status_code'] != 200:
        return resp
    print_sd_ctrl_result(client, resp)
    print('-' * 50)
    return resp


def print_sd_ctrl_result(client, resp):
    """
    功能描述：打印 请求结果
    参数：client (RedfishClient)
    resp (dict):redfish 接口返回值
    返回值：None
    异常描述：None
    修改：None
    """
    sd_ctrl = resp['resource'].get('StorageControllers', [])[0]
    # Export controller information.
    print(PF2.format('Id', sd_ctrl.get('MemberId', '')))
    print(PF2.format('Name', sd_ctrl.get('Name', '')))
    print('')
    print('[Status]')
    print(PF2.format('Health', sd_ctrl.get('Status', {}).get('Health', '')))
    print(PF2.format('State', sd_ctrl.get('Status', {}).get('State', '')))
    print('')
    print(PF2.format('FirmwareVersion', sd_ctrl.get('FirmwareVersion', '')))
    print(PF2.format('Manufacturer', sd_ctrl.get('Manufacturer', '')))
    if resp['resource'].get('Drives', {}):
        print('')
        print('[SDCard]')
        flag = False
        drive_array = resp['resource']['Drives']
        for drive_info in drive_array:
            url = drive_info['@odata.id']
            flag = True
            get_drive_info(client, url)
            if drive_info != drive_array[-1]:
                print('-' * 50)
        if not flag:
            print('Failure: resource was not found')
    else:
        print(PF2.format('[SDCard]', None))


def get_drive_info(client, url):
    """
    #==========================================================================
    #   @Method:  Obtain SD information.
    #   @Param:   client, RedfishClient client; uri: SD card URL
    #   @Return:  resp
    #   @author:
    #==========================================================================
    """
    drive_resp = client.get_resource(url)
    if drive_resp is None:
        return None
    if drive_resp['status_code'] != 200:
        return drive_resp

    drive_info = drive_resp['resource']
    sd_id = url.split(r'/')[6][-1]
    print(PF2.format('Id', sd_id))
    print(PF2.format('Name', 'SDCard' + sd_id))
    print(PF2.format('Manufacturer', drive_info.get('Manufacturer', '')))
    print(PF2.format('Revision', drive_info.get('Revision', '')))
    print(PF2.format('CapacityBytes', drive_info.get('CapacityBytes', '')))
    print(PF2.format('SerialNumber', drive_info.get('SerialNumber', '')))
    vendor_dict = common_function.get_vendor_value(drive_resp)
    print(PF2.format('Type', vendor_dict.get('Type', '')))
    print(PF2.format('RebuildState',
                     vendor_dict.get('RebuildState', '')))
    print('\n[Status]')
    print(PF2.format('Health', drive_info.get('Status', {}).get('Health', '')))
    print(PF2.format('State', drive_info.get('Status', {}).get('State', '')))

    return drive_resp
