# -*- coding: utf-8 -*-
"""
Function: get_session.py moudle. This moudle mainly involves the
Querying Session Resource Information function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2019-2020
"""
from scripts import common_function

LEN = 32
M_FORMAT = '%-*s:%-*s'


def getsession_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Querying Session Resource Information
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('getsession',
                                   help='''get session information''')
    sub_parser.add_argument('-I', dest='ID',
                            type=str, required=False,
                            help='''session ID''')
    parser_dict['getsession'] = sub_parser

    return 'getsession'


def get_session(client, member_id):
    """
    Function Description:Obtains a specified session.
    Parameter:client refishClient: class object
    member_id str:session ID
    """
    urltemp = "/redfish/v1/SessionService/Sessions/"
    urltemp = urltemp + ("%s" % member_id)

    resptemp = client.get_resource(urltemp)

    if resptemp is None:
        return None

    if resptemp['status_code'] == common_function.REDFISH_STATUS_CODE_200:
        print('-' * 60)
        print_session_info(resptemp)
    elif resptemp['status_code'] == common_function.REDFISH_STATUS_CODE_404:
        print('Failure: the session does not exist')
        return resptemp
    else:
        common_function.get_error_info(resptemp)

    return resptemp


def print_session_info(resptemp):
    """
    Function Description:Print session info.
    Parameter:resource dict: redfish Interface Value
    """
    resource = resptemp['resource']
    session_id = resource.get('Id', '')
    name = resource.get('Name', '')
    user_account = ""
    login_time = ""
    user_ip = ""
    user_tag = ""
    my_session = ""
    user_id = ""
    user_valid_days = ""
    account_insecure_prompt_enabled = ""
    user_role = ""
    # Modify: 2019.5.21. Check whether the key value exists.
    if "Oem" in resource and common_function.COMMON_KEY in resource.get("Oem"):
        res_inner_dic = common_function.get_vendor_value(resptemp)
        user_account = res_inner_dic.get("UserAccount", "")
        login_time = res_inner_dic.get("LoginTime", "")
        user_ip = res_inner_dic.get("UserIP", "")
        user_tag = res_inner_dic.get("UserTag", "")
        my_session = res_inner_dic.get("MySession", "")
        user_id = res_inner_dic.get("UserId", "")
        user_valid_days = res_inner_dic.get("UserValidDays", "")
        account_insecure_prompt_enabled = res_inner_dic.get(
            "AccountInsecurePromptEnabled", "")

        role_values = res_inner_dic.get("UserRole", "")
        if isinstance(role_values, list):
            user_role = ",".join(role_values)

    print(M_FORMAT % (LEN, 'ID', LEN, session_id))
    print(M_FORMAT % (LEN, 'Name', LEN, name))
    print(M_FORMAT % (LEN, 'UserAccount', LEN, user_account))
    print(M_FORMAT % (LEN, 'LoginTime', LEN, login_time))
    print(M_FORMAT % (LEN, 'UserIP', LEN, user_ip))
    print(M_FORMAT % (LEN, 'UserTag', LEN, user_tag))
    print(M_FORMAT % (LEN, 'MySession', LEN, my_session))
    print(M_FORMAT % (LEN, 'UserId', LEN, user_id))
    print(M_FORMAT % (LEN, 'UserValidDays', LEN, user_valid_days))
    print(M_FORMAT %
          (LEN, 'AccountInsecurePromptEnabled', LEN,
           account_insecure_prompt_enabled))
    print(M_FORMAT % (LEN, 'UserRole', LEN, user_role))
    print('-' * 60)


def get_sessions(client):
    """
    Function Description: Obtain all sessions.
    Parameter:client refishClient: class object
    Return Value: resp dict:result of the redfish interface
    """
    url = "/redfish/v1/SessionService/Sessions/"
    resp = client.get_resource(url)
    if resp is None:
        return None
    if resp['status_code'] == common_function.REDFISH_STATUS_CODE_200:
        result, flag = print_sessions(client, resp)
        if not flag:
            return result
    else:
        common_function.get_error_info(resp)

    return resp


def print_sessions(client, resp):
    """
    Function Description: print result.
    Parameter:client refishClient: class object
    resp dict:Redfish Interface Value
    """
    session_members = resp['resource']['Members']
    if not session_members:
        print("no data available for the resource")
        return resp, False
    print('-' * 60)
    for member in session_members:
        urltemp = member["@odata.id"]
        resptemp = client.get_resource(urltemp)
        if resptemp is None:
            return None, False
        if resptemp['status_code'] != common_function.REDFISH_STATUS_CODE_200:
            common_function.get_error_info(resptemp)
            return resptemp, False
        print_session_info(resptemp)
    return None, True


def getsession(client, args):
    """
    Function Description:Querying Session Resource Information
    Parameter:client refishClient: class object
    args object:CLI command
    """
    if args.ID is None:
        return get_sessions(client)
    return get_session(client, args.ID)
