# -*- coding:utf-8 -*-
"""
Function: restore_factory.py moudle. This moudle mainly involves the
Restoring the iBMC Factory Settings function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2018-2020
"""
from scripts.common_function import REDFISH_STATUS_CODE_200
from scripts.common_function import get_error_info
from scripts import common_function


def restorefactory_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Restoring the iBMC Factory Settings
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('restorefactory',
                                   help='''restore iBMC factory settings.''')

    parser_dict['restorefactory'] = sub_parser

    return 'restorefactory'


def restorefactory(client, _):
    """
    Function Description:Restarting the iBMC
    Parameter:client refishClient:class object
    """
    slotid = client.get_slotid()

    if slotid is None:
        return None

    try:
        # print default IP
        resp_print = print_default_ip(client, slotid)
    except (KeyError, IndexError):
        print("Failure: Get default IP error")
        return None

    if resp_print is None:
        return None

    if resp_print['status_code'] != REDFISH_STATUS_CODE_200:
        return resp_print

    url = "/redfish/v1/Managers/%s/Actions/" \
          "Oem/%s/Manager.RestoreFactory" % (slotid,
                                             common_function.COMMON_KEY)
    payload = {}
    resp = client.create_resource(url, payload)

    if resp is None:
        return None

    if resp['status_code'] == REDFISH_STATUS_CODE_200:
        print("Success: successfully completed request")
    else:
        get_error_info(resp)

    return resp


def print_default_ip(client, slotid):
    """
    Function Description:print default IP
    Parameter:client refishClient:class object
    slotid str:manager id
    """
    url = "/redfish/v1/Managers/%s" % slotid
    resp = client.get_resource(url)

    if resp is None:
        return None

    if resp['status_code'] == REDFISH_STATUS_CODE_200:
        vendor_dict = common_function.get_vendor_value(resp)
        default_ip = vendor_dict.get('DefaultIPv4Info')
        if default_ip:
            print("Default IP:")
            print("  IPMode:", default_ip['IPMode'])
            print("  IPv4Address:", default_ip['IPv4Address'])
    else:
        get_error_info(resp)

    return resp
