# -*- coding:utf-8 -*-
"""
Function: set_protocol.py moudle. This moudle mainly involves the
 setting the In-band Communication Protocol Between uREST and iBMC function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2018-2021
"""
import re
import os
import sys

from scripts import common_function


def setprotocol_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    setting the Communication Protocol Between uREST and iBMC.
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    Modify:  2019.4.28 The help information is optimized.
    Return Value: subcommand
    """
    sub_parser = parser.add_parser('setprotocol',
                                   help='''set uREST to support communication
                                    with iBMC in IPv4 mode.''')
    sub_parser.add_argument('-M', dest='CommunicationMethod', required=True,
                            action=common_function.UniqueStore,
                            help='''communication method IPv6 or IPv4''',
                            choices=[common_function.IPV4,
                                     common_function.IPV6])
    sub_parser.add_argument('-I', dest='iBMCIp', required=False,
                            action=common_function.UniqueStore,
                            help='''user has configured iBMC IP''', )
    parser_dict['setprotocol'] = sub_parser

    return 'setprotocol'


def get_value(key, content):
    """
    Function Description:get key's value
    Parameter:content str: file content
    key str:mode or key
    """
    if key == "mode":
        regular_line = common_function.REGULAR_MODE_LINE
        regular_key = common_function.REGULAR_MODE_KEY
    else:
        regular_line = common_function.REGULAR_IP_LINE
        regular_key = common_function.REGULAR_IP_KEY

    value_keys = re.findall(regular_key, content) if content else None
    ibmc_lines = re.findall(regular_line, content) if value_keys else None
    value = str(ibmc_lines[0]).replace(
        str(value_keys[0]), "") if ibmc_lines and value_keys else None
    return value.replace("\'", "") if value else None


def edit_code(mode, bmc_ip):
    """
    Modify redfish_client.py
    :param mode:Communication mode
    :param bmc_ip:ip address
    :return:
    """
    try:
        cur_path = os.path.split(os.path.realpath(__file__))[0]
        pos = cur_path.rfind('scripts')
        rest_path = cur_path[0:pos]
        redfish_path = rest_path + 'redfish'
        file_path = redfish_path + '//redfish_client.py'
        with open(file_path, 'r+', encoding='utf-8') as f:
            file_content = f.read()

            old_mode = get_value("mode", file_content)
            old_ip = get_value("ip", file_content)

        file_content = re.sub(common_function.REGULAR_MODE_LINE,
                              "ibmcmode = '%s'" % mode, file_content)
        file_content = re.sub(common_function.REGULAR_IP_LINE,
                              "ibmcip = '%s'" % bmc_ip, file_content)
        common_function.write_file(file_path=file_path,
                                   file_content=file_content)
        return [old_mode, old_ip]
    except OSError:
        print("Setting urest to communicate with BMA failed!")
        sys.exit(common_function.UREST_STATUS_CODE_127)


def check_parameter(parser, args):
    """
    Function Description:check CLI command
    Parameter:args object:CLI command
    parser object:subcommand ArgumentParser object
    """
    mode = args.CommunicationMethod
    bmc_ip = args.iBMCIp
    if mode == "IPv4":
        if bmc_ip is None:
            parser.error("The ip address cannot be empty. "
                         "Please enter the IP address.")

        p = re.compile(r'^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}'
                       r'(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
        if not p.match(bmc_ip):
            parser.error("The IPv4 address format is incorrect."
                         " Please enter the correct IP address.")

    if args.CommunicationMethod == "IPv6":
        if bmc_ip is not None:
            parser.error("-I is not needed parameter.")


def setprotocol(client, _):
    """
    Function Description:Setting the Communication Protocol
    Between uREST and iBMC
    Parameter:client refishClient: class object
    Return Value:resp dict:redfish value
    """
    # Detection interface
    url = "/redfish/v1"
    resp = client.get_resource(url)
    if resp is None:
        return None

    if resp['status_code'] == 200:
        print('Success: successfully completed request')
    else:
        error_code = "0"
        if resp['status_code']:
            error_code = resp['status_code']
        print('Failure: error code ' + error_code)
        return None
    return resp
