###################################################################
# Copyright 2015 Freescale Semiconductor, Inc.
# Copyright 2018, 2020, 2022-2025 NXP
# SPDX-License-Identifier: BSD-3-Clause

import sys
import os

#compute gdb_extensions absolute path
FLASH_EXT_INSTALL_DIR = ''.join([os.path.dirname(os.path.realpath(__file__)), '/'])
GDB_EXT_INSTALL_DIR =''.join([FLASH_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, FLASH_EXT_INSTALL_DIR + "../../utils")

from flash.scripts.services import start_fp_services
from errors import ErrorCode, exceptcall
import check_global_variables as cgv

# Global parameters are checked only once.
isCheckedGlobalParameters = False

# Check global parameters
def check_fp_global_parameters():
    global isCheckedGlobalParameters
    if isCheckedGlobalParameters:
        return
    cgv.check_fp_global_parameters(globals()).unwrap()
    isCheckedGlobalParameters = True

###################################################################
######### Set Flash Programmer Parameters
###################################################################
def setup(
                      # Mandatory arguments
                      soc_name,
                      flash_type,
                      flash_name,
                      init_script,
                      probe_ip, 
                      # Optional arguments
                      jtag_speed = 16000,
                      gdb_server_port = 45000,
                      gdb_timeout = 7200,
                      reset_delay = 2,
                      reset_type = "default",
                      is_logging_enabled = True,
                      secure_type = None,
                      secure_key = None,
                      lifecycle = None,
                      ccs_ip = None,
                      ccs_port = None,
                      resultexception = True):

    global _SOC_NAME, _FLASH_TYPE, _FLASH_NAME, _INIT_SCRIPT, _PROBE_IP
    global _JTAG_SPEED, _GDB_SERVER_PORT, _GDB_TIMEOUT, _RESET_DELAY, _RESET_TYPE
    global _IS_LOGGING_ENABLED, _SECURE_TYPE, _SECURE_KEY, _LIFECYCLE, _CCS_IP, _CCS_PORT, _RESULTEXCEPTION
    
    # SOC name
    _SOC_NAME = soc_name

    # Flash types (Supported values: "qspi" , "ifc").
    # For external flash memories, use qspi
    # For internal flash memories, use ifc
    _FLASH_TYPE = flash_type

    # Flash name
    _FLASH_NAME = flash_name
    
    # Script that used to initialize target
    _INIT_SCRIPT = init_script
    
    # Probe IP. For usb connection, use MAC address
    _PROBE_IP = probe_ip

    # JTAG speed, default value 16000Khz
    _JTAG_SPEED = jtag_speed

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

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

    # Reset settings
    _RESET_DELAY = reset_delay #  Default value 2 seconds
    _RESET_TYPE = reset_type   #  Default value True

    # Logging enabled.  Default value True
    _IS_LOGGING_ENABLED = is_logging_enabled

    # Secure debug variables.  Default disabled
    if secure_type is not None:
        _SECURE_TYPE = secure_type
    else:
        cgv.iff_undef_gvar("_SECURE_TYPE", None, globals())
    if secure_key is not None:
        _SECURE_KEY = secure_key
    else:
        cgv.iff_undef_gvar("_SECURE_KEY", None, globals())
    if lifecycle is not None:
        _LIFECYCLE = lifecycle
    else:
        cgv.iff_undef_gvar("_LIFECYCLE", None, globals())
    if ccs_port is not None:
        _CCS_PORT = ccs_port    #  Default value 41475  
    else:
        cgv.iff_undef_gvar("_CCS_PORT", 41475, globals())
    if ccs_ip is not None:
        _CCS_IP = ccs_ip
    else:
        cgv.iff_undef_gvar("_CCS_IP", "127.0.0.1", globals())
    
    # Extended exceptions stacks. Default value True
    _RESULTEXCEPTION = resultexception
    

###################################################################
######### Start Flash Programming Services
###################################################################
@exceptcall(ErrorCode.FlashUndefinedError)
def _fp_initialization():
    """
        CodeWarrior services initialization script
    """
    gtaip = _GDB_SERVER_PORT
    
    dev_arg = '-d %s' % _FLASH_TYPE

    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
    
    init_script = '--init "%s"' % _INIT_SCRIPT
    
    flash = '--flash_name %s' % _FLASH_NAME
    
    log = '--log %s' % _IS_LOGGING_ENABLED

    soc_name = '--soc_name %s' % _SOC_NAME

    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)

    core_name = '--core_name %s' % _CORE_NAME if _CORE_NAME else ''

    argument = ' '.join([dev_arg, conn_arg, gtaip_arg, jtag_speed_arg, timeout_arg, \
        reset_delay, reset_type, init_script, flash, log, soc_name, core_name, secure_type, secure_key, \
        ccsip])
        
    start_fp_services(argument)

    
def flash():
    check_fp_global_parameters()
    import settings
    settings.ResultException = _RESULTEXCEPTION
    _fp_initialization().unwrap()
    
def reset():
    from flash.scripts.services import reset_board
    reset_board(_INIT_SCRIPT)
