# -*- coding: utf-8 -*-
"""
Function: import_syslog_cert.py moudle. This moudle mainly involves the
 importing a Syslog Certificate function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2020-2021
"""
import sys
import time

from scripts import common_function


def importsyslogcert_init(parser, parser_dict):
    """
    Function Description:import syslog certificate subcommand init
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    Modify: The -F parameter is added.
            2019.4.28 The help information is optimized.
    Return Value: subcommand
    """
    sub_parser = parser.add_parser('importsyslogcert',
                                   help='''import syslog certificate''')

    sub_parser.add_argument('-T', dest='Type',
                            required=True, choices={'root', 'client'},
                            help='''the type of certificate''')

    sub_parser.add_argument('-C', dest='Content',
                            type=str, required=False, default=None,
                            help='path of the Syslog certificate.'
                                 ' On a local file server, the'
                                 ' certificate can be stored only'
                                 ' in the /tmp directory of iBMC,'
                                 ' and the path format is'
                                 ' /tmp/file name.'
                                 ' On a remote file server,'
                                 ' the path format is protocol://'
                                 'User name:Password@IP address/'
                                 'Folder/File name. The file '
                                 'transfer protocols include the'
                                 ' following: sftp, https, nfs,' 
                                 ' cifs, scp.')

    sub_parser.add_argument('-F', dest='file', required=False,
                            help='the path of file. Local '
                                 'import:Folder/File name.\n\r')

    sub_parser.add_argument('-P', dest='CertPassword',
                            type=str, required=False, default=None,
                            help='the password of client '
                                 'encrypted certificate')

    sub_parser.add_argument('-E', dest='CertPasswordEnable',
                            type=str, required=False,
                            choices=["True", "False"],
                            default="False",
                            help='specifies whether to enter the customized '
                                 'Syslog certificate encryption password')

    image_uri = {common_function.REQUIRED_FLAG: False,
                 common_function.HELP_INFO: 'path of the Syslog certificate.'
                                            ' On a local file server, the'
                                            ' certificate can be stored only'
                                            ' in the /tmp directory of iBMC,'
                                            ' and the path format is'
                                            ' /tmp/file name.'
                                            ' On a remote file server,'
                                            ' the path format is server'
                                            ' IP address/directory/file name.'}
    args_pro = {common_function.REQUIRED_FLAG: False}
    args_acc = {common_function.REQUIRED_FLAG: False}
    common_function.unpack_remote_server_path(sub_parser, image_uri,
                                              args_pro, args_acc)

    parser_dict['importsyslogcert'] = sub_parser

    return 'importsyslogcert'


def _resptaskparse(resp, client):
    """
    #====================================================================
    #   @Description:  parse response code and body
    #
    #   @Date: 2017.08.31 09:11
    #====================================================================
    """

    taskid = resp['resource']['@odata.id']

    sys_resp = client.get_resource(taskid)
    if sys_resp is None:
        sys.exit(127)

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


def _respparse(resp):
    """
    #=====================================================================
    #   @Description:  parse response code and body
    #
    #   @Date: 2017.08.31 09:12
    #=====================================================================
    """
    if resp['status_code'] == 200:
        print('Success: successfully completed request\r')
    else:
        messageid = resp['message']['error']['@Message.ExtendedInfo'][0].get(
            'MessageId')
        if 'Format' in messageid:
            print('Failure: import failed due to invalid path')
        else:
            message = (
                resp['message']['error']['@Message.ExtendedInfo'][0].get(
                    'Message')).lower()
            print('Failure: ' + message[:-1])


def importsyslogcert(client, args):
    """
    #=====================================================================
    #   @Description:  import syslog certificate
    #
    #   @Date:
    #   @Modify: Modify the variable name of the receiving progress
    #   @Modify: The local import function is added.
    #=====================================================================
    """
    file_path = get_file_path(args, client)
    payload = {"Type": "URI", "Content": file_path}
    if args.Type == 'client':
        if args.CertPassword is not None:
            payload["Password"] = args.CertPassword
        elif args.CertPasswordEnable == 'True':
            payload["Password"] = common_function.subcommand_pwd("Syslog Cert", True)

    slotid = client.get_slotid()
    if slotid is None:
        return None

    url = get_url(args, slotid)
    resp = client.create_resource(url, payload)

    if resp is None:
        return None

    if resp.get('status_code') == 202:
        time.sleep(1)
        resp_task = client.print_task_prog(resp)
        if resp_task is None:
            return None

        if resp_task == 'Exception':
            _resptaskparse(resp, client)
            sys.exit(144)

    else:
        _respparse(resp)

    return resp


def get_file_path(args, client):
    """
    Function Description: get file path
    Parameter:client redfishClient
    args object:CLI command
    Return Value: file_path
    """
    if args.Content is not None:
        file_path = args.Content
    elif args.file is not None:
        file_path = common_function.import_file_path(client, args.file)
    else:
        file_path = common_function.splice_remote_server_path(args)

    if file_path is None:
        sys.exit(2)

    return file_path


def get_url(args, slotid):
    """
    功能描述:根据Syslog证书类型初始化url
    参数：args (list): parameter list
    slotid (str): 服务器类型
    返回值：None
    修改：None
    """
    url = None
    syslogservice_action_url = \
        "/redfish/v1/Managers/%s/SyslogService/Actions" % slotid
    if args.Type == 'root':
        url = "%s/SyslogService.ImportRootCertificate" \
              % syslogservice_action_url
    elif args.Type == 'client':
        url = "%s/SyslogService.ImportClientCertificate" \
              % syslogservice_action_url
    return url


def check_parameter(_, args):
    """
    Function Description:check CLI command
    Parameter:args object:CLI command
    parser object:subcommand ArgumentParser object
    """
    if args.CertPassword is not None and args.CertPasswordEnable == 'True':
        print('-E is not needed in non-interactive command')
        sys.exit(common_function.UREST_STATUS_CODE_2)
    if (args.imageuri is not None or args.protocol is not None or
            args.accessuser is not None) and args.Content is not None:
        print("Failure: -C contains the information of -i -PRO and -U. you can not use -C and -i -PRO -U both.")
        sys.exit(common_function.UREST_STATUS_CODE_2)
    if args.Content is not None and not (common_function.verify_remote_server_info(args.Content)
             or args.Content.startswith("/tmp")):
        print('Failure: path of the Syslog certificate.'
              ' On a local file server, the'
              ' certificate can be stored only'
              ' in the /tmp directory of iBMC,'
              ' and the path format is'
              ' /tmp/file name.'
              ' On a remote file server,'
              ' the path format is protocol://'
              'User name:Password@IP address/'
              'Folder/File name. The file '
              'transfer protocols include the'
              ' following: sftp, https, nfs,' 
              ' cifs, scp.')
        sys.exit(common_function.UREST_STATUS_CODE_2)


def is_interactive(args):
    """
    Function Description:check CLI command
    Parameter:args object:CLI command
    parser object:subcommand ArgumentParser object
    """
    if args.Content is not None:
        return False
    return True
