# -*- coding:utf-8 -*-
"""
Function: get_ip.py moudle. This moudle mainly involves the
Querying IP Address 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

FORMAT = '%-20s: %s'


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

    return 'getip'


def get_ip_info(members_uri, client):
    """
    Function Description:Query IP address information.
    Parameter:members_uri str:members uri
    client refishClient: class object
    """
    resp_ip = client.get_resource(members_uri)
    if resp_ip is None:
        return None
    if resp_ip['status_code'] != REDFISH_STATUS_CODE_200:
        if resp_ip['status_code'] == REDFISH_STATUS_CODE_404:
            print('Failure: resource was not found')
        return resp_ip

    vendor_info = common_function.get_vendor_value(resp_ip)
    ip_version = vendor_info.get("IPVersion", '')
    ipv4_addresses = resp_ip["resource"].get("IPv4Addresses", '')
    ipv6_addresses = resp_ip["resource"].get("IPv6Addresses", '')
    # Display information.
    print("")
    print(FORMAT % ("IPVersion", ip_version))
    print(FORMAT %
          ("PermanentMACAddress", resp_ip['resource'].get("PermanentMACAddress", '')))
    print(FORMAT %
          ("IPv6DefaultGateway", resp_ip['resource'].get("IPv6DefaultGateway", '')))
    print("\n[IPv4Addresses]")
    print("-" * 40)
    idx = 0
    while idx < len(ipv4_addresses):
        for key in ipv4_addresses[idx]:
            print(FORMAT % (key, ipv4_addresses[idx][key]))
        print("-" * 40)
        idx += 1
    print("\n[IPv6Addresses]")
    idx = 0
    print("-" * 40)
    while idx < len(ipv6_addresses):
        for key in ipv6_addresses[idx]:
            print(FORMAT % (key, ipv6_addresses[idx][key]))
        idx += 1
        print("-" * 40)
    return resp_ip


def get_port_collection(client, slotid):
    """
    Function Description:Query collection information.
    Parameter:client refishClient:class object
    slotid str:manager id
    """
    url = "/redfish/v1/managers/%s/EthernetInterfaces" % slotid
    resp_ip = client.get_resource(url)
    if resp_ip is None:
        return None
    if resp_ip['status_code'] != REDFISH_STATUS_CODE_200:
        if resp_ip['status_code'] == REDFISH_STATUS_CODE_404:
            print('Failure: resource was not found')
        return resp_ip
    # 200 message
    members_count = resp_ip['resource'].get("Members@odata.count", {})
    if members_count == 0:
        print("no data available for the resource")
    # Query DNS information.
    else:
        members_uri = resp_ip['resource'].get('Members', {})[0]["@odata.id"]
        resp_ip = get_ip_info(members_uri, client)
    return resp_ip


def getip(client, _):
    """
    Function Description:Querying IP Address Information
    Parameter:client refishClient:class object
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None
    # Query collection information.
    ret = get_port_collection(client, slotid)

    return ret
