# -*- coding:utf-8 -*-
"""
Function: add_csr.py moudle. This moudle mainly involves the
Generating a CSR function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2017-2020
"""
import sys
from scripts.common_function import REDFISH_STATUS_CODE_200
from scripts.common_function import REDFISH_STATUS_CODE_202
from scripts.common_function import UREST_STATUS_CODE_127
from scripts.common_function import UREST_STATUS_CODE_144


def addcsr_init(parser, parser_dict):
    """
    Function Description:initializing the Command for Generating a CSR
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('addcsr',
                                   help='generate certificate signing request')
    sub_parser.add_argument('-CO', dest='Country',
                            type=str, required=True,
                            help='''country, consist of two characters''')
    sub_parser.add_argument('-S', dest='State',
                            type=str, required=False, help='''state''')
    sub_parser.add_argument('-CI', dest='City',
                            type=str, required=False, help='''city''')
    sub_parser.add_argument('-ON', dest='OrgName',
                            type=str, required=False,
                            help='''organizations name''')
    sub_parser.add_argument('-OU', dest='OrgUnit',
                            type=str,
                            required=False,
                            help='''organizations unit''')
    sub_parser.add_argument('-CN', dest='CommonName',
                            type=str,
                            required=True,
                            help='''common name''')

    parser_dict['addcsr'] = sub_parser

    return 'addcsr'


def _resptaskparse(resp, client):
    """
    Function Description: parse response code and body
    Parameter:resp dict:redfish interface value
    client refishClient: class object
    """
    taskid = resp['resource']['@odata.id']

    add_resp = client.get_resource(taskid)
    if add_resp is None:
        sys.exit(UREST_STATUS_CODE_127)

    if add_resp['status_code'] != REDFISH_STATUS_CODE_200:
        message = (add_resp['message']['error']['@Message.ExtendedInfo'][0][
            'Message']).lower()
        print('Failure: ' + message[:-1])
    else:
        message = (add_resp['resource']['Messages']['Message']).lower()
        print('Failure: ' + message[:-1])


def _respparse(resp):
    """
    Function Description: parse response code and body
    Parameter:resp dict:redfish interface value
    """
    if resp['status_code'] == REDFISH_STATUS_CODE_200:
        print('Success: successfully completed request\r')

    else:
        print_err_result(resp)


def print_err_result(resp):
    """
    Function Description: print error result
    Parameter:resp dict:redfish interface value
    """
    msgs = resp['message']['error']['@Message.ExtendedInfo']
    messageid = msgs[0].get('MessageId')
    if 'CSRGenFailed' in messageid:
        print('Failure: %s' % (msgs[0].get('Message')))
    i = 0
    for msg_info in msgs:
        len_msg = len(msg_info['RelatedProperties'])
        if len_msg == 0 and len(msg_info['MessageArgs'][1]) >= 2:
            msg = msg_info['MessageArgs'][1]

        if i == 0:
            print('Failure: invalid property %s value' % msg)
        else:
            print('         invalid property %s value' % msg)
        i = i + 1


def addcsr(client, args):
    """
    Function Description: Generating a CSR
    Parameter:client refishClient:class object
    args object:CLI command
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None

    payload = init_payload(args)

    url = "/redfish/v1/managers/%s/SecurityService/" % slotid + \
          "HttpsCert/Actions/HttpsCert.GenerateCSR"
    resp = client.create_resource(url, payload)

    if resp is None:
        return None

    if resp['status_code'] == REDFISH_STATUS_CODE_202:

        resp_task = client.print_task_prog(resp, 5)
        if resp_task is None:
            return None
        if resp_task == 'Exception':
            _resptaskparse(resp, client)
            sys.exit(UREST_STATUS_CODE_144)

    else:
        _respparse(resp)

    return resp


def init_payload(args):
    """
    Function Description: init payload
    Parameter:args object:CLI command
    Return Value: payload dict
    """
    payload = {}
    if args.Country is not None:
        payload['Country'] = args.Country
    if args.State is not None:
        payload['State'] = args.State
    if args.City is not None:
        payload['City'] = args.City
    if args.OrgName is not None:
        payload['OrgName'] = args.OrgName
    if args.OrgUnit is not None:
        payload['OrgUnit'] = args.OrgUnit
    if args.CommonName is not None:
        payload['CommonName'] = args.CommonName
    return payload
