# -*- coding:utf-8 -*-
"""
Function: get_vlan.py moudle. This moudle mainly involves the
 querying VLAN Information function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2020-2021
"""
FORMAT = '%-20s: %s'


def getvlan_init(parser, parser_list):
    """
    #===========================================================
    # @Method:Register command functions.
    # @Param: parser, parser_list
    # @Return:
    # @date: 2017.8.1
    #===========================================================
    """
    sub_parser = parser.add_parser('getvlan',
                                   help='''get VLAN information''')
    parser_list['getvlan'] = sub_parser

    return 'getvlan'


def get_vlan_info(members_uri, client):
    """
    #===========================================================
    # @Method:  Query VLAN information.
    # @Param:client, slotid
    # @Return:
    # @date: 2017.8.1 11:15
    #===========================================================
    """
    resp_vl = client.get_resource(members_uri)
    if resp_vl is None:
        return None
    if resp_vl['status_code'] != 200:
        if resp_vl['status_code'] == 404:
            print('Failure: resource was not found')
        return resp_vl
    vlan_info = resp_vl["resource"].get("VLAN", None)
    if vlan_info is None:
        print('no data available for the resource')
        return vlan_info

    # Query VLAN information.
    print("")
    for key in vlan_info:
        print(FORMAT % (key, vlan_info[key]))
    return resp_vl


def get_port_collection(client, slotid):
    """
    #===========================================================
    # @Method: Collection information query
    # @Param:client, slotid
    # @Return:
    # @date: 2017.8.1
    #===========================================================
    """
    url = "/redfish/v1/managers/%s/EthernetInterfaces" % slotid
    resp_vl = client.get_resource(url)
    if resp_vl is None:
        return None
    if resp_vl['status_code'] != 200:
        if resp_vl['status_code'] == 404:
            print('Failure: resource was not found')
        return resp_vl
    members_count = resp_vl['resource'].get("Members@odata.count", {})
    if members_count == 0:
        print("no data available for the resource")
        return resp_vl
    # Query VLAN information.
    members_uri = resp_vl['resource']['Members'][0]["@odata.id"]
    resp_vl = get_vlan_info(members_uri, client)
    return resp_vl


def getvlan(client, _):
    """
    #===========================================================
    # @Method: VLAN command processing function
    # @Param:client
    # @Return:
    # date:2017.08.29 11:43
    #===========================================================
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None
    ret = get_port_collection(client, slotid)

    return ret
