# -*- coding: utf-8 -*-
"""

Copyright 2024 NXP
SPDX-License-Identifier: BSD-3-Clause

"""
###################################################################
######### Parameters
###################################################################

# Connection probe. Possible values:
_PROBE_IP = "10.222.24.64"

# JTAG speed.
_JTAG_SPEED = 16000

# Address:port that will be used by GTA.
_GDB_SERVER_PORT = 45000

# Remote target responses time-out (seconds).
_GDB_TIMEOUT = 7200

# Specific RCON target script
_RCON_SCRIPT = ""

#Reset settings
_RESET_DELAY = 2
_RESET_TYPE = 'default'

_IS_LOGGING_ENABLED = False

# initialize secure debug variables
_SECURE_TYPE = None
_SECURE_KEY = None
_LIFECYCLE = None

# CCS variables
_CCS_IP = "127.0.0.1"
_CCS_PORT = 41475

_RESULTEXCEPTION = True

###################################################################
######### Start RCON Programming Services
###################################################################
import sys
import os

#compute gdb_extensions absolute path
RCON_EXT_INSTALL_DIR = ''.join([os.path.dirname(os.path.realpath(__file__)), '/'])
GDB_EXT_INSTALL_DIR =''.join([RCON_EXT_INSTALL_DIR, '../'])


#add gdb_extensions to system path
sys.path.insert(0, GDB_EXT_INSTALL_DIR)
#add path to utils
sys.path.insert(0, RCON_EXT_INSTALL_DIR + "../../utils")

from rcon.scripts.services import start_rcon_services
from errors import ErrorCode, exceptcall

@exceptcall(ErrorCode.RCONUndefinedError)
def _rcon_initialization():
    """
        RCON services initialization script
    """
    gtaip = _GDB_SERVER_PORT

    conn_arg = ''
    if _PROBE_IP:
        conn_arg = '--probe %s' % _PROBE_IP

    gtaip_arg = ''
    if gtaip:
        gtaip_arg = '--gtaip %d' % gtaip

    jtag_speed_arg = '--jtag_speed %d' % _JTAG_SPEED
    timeout_arg = '--timeout %d' % _GDB_TIMEOUT
    
    reset_delay = '--reset_delay %d' % _RESET_DELAY
    reset_type = '--reset_type %s' % _RESET_TYPE

    rcon_script = '--rconscript %s' %_RCON_SCRIPT
    
    log = '--log %s' % _IS_LOGGING_ENABLED

    secure_type = '--secure_type %s' % _SECURE_TYPE if _SECURE_TYPE else ''

    secure_key = '--secure_key %s' % _SECURE_KEY if _SECURE_KEY else ''

    target_lifecycle = '--target_lifecycle %s' % _LIFECYCLE if _LIFECYCLE else ''

    ccsip = '--ccsip %s:%s' % (_CCS_IP, _CCS_PORT)

    argument = ' '.join([conn_arg, gtaip_arg, jtag_speed_arg, timeout_arg, \
        reset_delay, reset_type, rcon_script, log, secure_type, secure_key, \
        ccsip])
    start_rcon_services(argument)

    
def rcon():
    import settings
    settings.ResultException = _RESULTEXCEPTION
    
    _rcon_initialization().unwrap()
    