########## BEGIN SCONSTRUCT ##########

from scons_common import ncpus
from typing import List
import os
import sys
sys.path.append(Dir('#').abspath + "\\Build\\FreeRtos_mcu1_community\\site_scons\\site_tools")
sys.path.append(Dir('#').abspath + "\\Build\\FreeRtos_mcu1_community\\site_scons\\site_tools")


# Ensure tool versions
EnsurePythonVersion(2, 7)
EnsureSConsVersion(3, 0, 0)

# Settings file to be read
settings_file = os.sep.join(['.', 'Build', 'FreeRtos_mcu1_community', 'settings_freertos.py'])
# Add one customized command to generate list of include path which is used for generate configuration for QAC
AddOption('--util', action='store_true')
# Configure number of CPU to compile the source code.
SetOption('num_jobs', ncpus())


def add_component(env, path_folder_list: List[str], duplicate: bool) -> List[str]:
    """
    Add build component by formating comp_build_dir/comp_sconscript_path
    and calling SConscript()

    Args:
        env (Scons Environment()): Build environment class from Scons
        path_folder_list (list[str]): List of Path folders of component relative to mcu/
        duplicate (bool): Sconscript "duplicate" option

    Returns:
        list[str]: Objects pending compile
    """
    comp_sconscript_path = ""
    comp_build_dir = "objs"

    for path_folder in path_folder_list:
        comp_build_dir = os.path.join(comp_build_dir, path_folder)
        comp_sconscript_path = os.path.join(comp_sconscript_path, path_folder)

    comp_sconscript_path = os.path.join(comp_sconscript_path, "SConscript")
    comp_build_dir = os.path.join(env.subst('$OUTPUT_DIR'), comp_build_dir)

    return SConscript(comp_sconscript_path, exports='env',
                          variant_dir=comp_build_dir, duplicate=duplicate)


# Load all the variables into the environment
if not os.path.exists(settings_file):
    print('Could not find file ' + settings_file + ' in current directory.')
else:
    vars = Variables(settings_file)

    # Add variables to environment along with some help text
    vars.Add('OUTPUT_DIR',          'Path to Build all target files.', 'output')
    vars.Add('OUTPUT_BINARY_DIR',   'Path to Build all target files.')
    vars.Add('LIBRARY_DIR',         'Path to Build all target libraries.', 'Library')
    vars.Add('LOG_DIR',             'Path to store all log files.', 'log')
    vars.Add('CPU_TARGET',
             'CPU to Build for.  Must match what the compiler is expecting as \'cpu\' option.')
    vars.Add('CPU_ARCHI',
             'CPU to Build for.  Must match what the compiler is expecting as \'cpu\' option.')
    vars.Add('COMPILER_TOOL',
             'Custom SCons tool to be used for Building.  Must match the file name located in the site_tools directory.')
    vars.Add('COMPILER_ROOT',       'Path to compiler executables.')
    vars.Add('COMPILER_FLAGS',      'Compiler flags to use for Building.')
    vars.Add('COMPILER_DEFINES',    'Compiler defines to use for Building.')
    vars.Add('ASSEMBLER_FLAGS',     'Assembler flags to use for Building.')
    vars.Add('ASSEMBLER_DEFINES',   'Assembler defines to use for Building.')
    vars.Add('LINKER_FLAGS',        'Linker flags to be used for Building.')
    vars.Add('LINKER_FILE',
             'Path to linker file to be used during linking.')
    vars.Add('ADD_LIBRARIES',
             'Names of additional libraries to be included during linking.  These do not need the file extension.')
    vars.Add('LIBRARY_PATHS',       'Paths to look for the additional libraries.')
    vars.Add('BUILD_TYPE',
             'Type of Build to be done.  Options are: DEBUG, PROD, DEVEL')
    vars.Add('PROJ_NAME',           'Name of the project to be built.')
    vars.Add('OBJECT_FILE',
             'path to object files to be added during linking.')
    vars.Add('CEN_HEADER_DIR',      'path to centralized header file of project.')
    vars.Add('LIBRARY_SEARCH_PATH', 'Path to search a specific library')
    vars.Add('CPU_USED',        'CPU Used.')
    vars.Add('ASW_BUILD_EN', 'Asw .c .cpp build enable')
    vars.Add('SCONSCRIPT_RE_STR', 'Sconscript src path re substitute string.')
    # Initialize the default SCons environment
    env = Environment(variables=vars)

    # Generate variables help text
    env.Help(vars.GenerateHelpText(env))

    # to add the checking of SIMULATION BUILD from input command line
    simbuild = ARGUMENTS.get('SIMBUILD', 0)
    if int(simbuild):
        env.Append(COMPILER_DEFINES='__EPM_TRIGGER_SIMULATION=__EPM_TSIM_ON')
        print("************************************************************************************************")
        print("*               Enter ENGINE SIMULATION BUILD mode                                            *")
        print("* Compiler Preprocessor Macro option: %s *" %
              env['COMPILER_DEFINES'])
        print("************************************************************************************************")
if (not GetOption('help')) and (not GetOption('util')):

    import scons_common

    if sys.version_info.major == 3:
        import site_tools.prebuild
    else:
        import prebuild

    # Setup logging of output
    scons_common.setuplogging(env)

    # Validate the mandatory values of the environment
    scons_common.validate_environment(env)

    # Build target/project name
    if env['BUILD_TYPE'] == 'PROD':
        env['PROJ_PREFIX'] = 'P'
        # env['TARGET_NAME']       = env.subst('$PROJ_PREFIX') + '_' + env.subst('$PROJ_NAME') + '_V' + env.subst('$SW_VERSION_MSB') + '_' + env.subst('$SW_VERSION_LSB') + '_' + env.subst('$DATE_TIME')
    elif env['BUILD_TYPE'] == 'DEVEL':
        env['PROJ_PREFIX'] = 'R'
        # env['TARGET_NAME'] = env.subst('$PROJ_PREFIX') + '_' + env.subst('$PROJ_NAME') + '_V' + env.subst('$SW_VERSION_MSB') + '_' + env.subst('$SW_VERSION_LSB') + '_' + env.subst('$DATE_TIME')
    elif env["BUILD_TYPE"] == 'RELEASE':
        env['PROJ_PREFIX'] = 'R'
        env['PROJ_SUFFIX'] = 'RELEASE'
        # env['TARGET_NAME'] = env.subst('$PROJ_PREFIX') + '_' + env.subst('$PROJ_NAME') + '_V' + env.subst('$SW_VERSION_MSB') + '_' + env.subst('$SW_VERSION_LSB') + '_' + env.subst('$DATE_TIME')
    else:
        env['PROJ_PREFIX'] = 'D'
        env['PROJ_SUFFIX'] = 'DEBUG'
        # env['TARGET_NAME'] = env.subst('$PROJ_PREFIX') + '_' + env.subst('$PROJ_NAME') + '_V' + env.subst('$SW_VERSION_MSB') + '_' + env.subst('$SW_VERSION_LSB')

    # Just keep the name according to project - version is already identified by tag name
    env['TARGET_NAME'] = env.subst(
        '$PROJ_NAME') + '_' + env.subst('$PROJ_SUFFIX')
    ############ START SCONSCRIPT ############
    # clone the evironment and setup compiler specific enivronment
    env = env.Clone(tools=[env['COMPILER_TOOL']])
    env = env.Clone(tools=[env['COMPILER_TOOL'], 'memory_usage'])

    # remove all psuedo header file

    if sys.version_info.major == 3:
        site_tools.prebuild.cleanHeaderDir(env['CEN_HEADER_DIR'])
    else:
        prebuild.cleanHeaderDir(env['CEN_HEADER_DIR'])

    # Storage of all objects to be linked
    objects = []

# -------------------------------------------------------------------------------------------------------
    # Setup build directories for sub-systems
    env.Append(CPPPATH=[os.environ["INCLUDE_DIR"]])
    # env.Append(CPPPATH=["/home/users/hualun.dong/46/mcu/Include"])
    objects += add_component(env, ['samples', 'Can'], False)
    objects += add_component(env, ['samples', 'Uart'], False)
    objects += add_component(env, ['samples', 'Spi'], False)
    objects += add_component(env, ['samples', 'Pwm'], False)
    objects += add_component(env, ['samples', 'Eth'], False)
    objects += add_component(env, ['samples', 'Adc'], False)
    objects += add_component(env, ['samples', 'Gpio'], False)
    objects += add_component(env, ['Config', 'McalCdd', 'gen_s100_sip_B_mcu1'], False)
    objects += add_component(env, ['OpenSource'], False)
    # objects += add_component(env, ['samples', 'Ipc'], False)
    objects += add_component(env, ['Target', 'Target-hobot-lite-freertos-mcu1'], False)
    objects += add_component(env, ['samples', 'test'], False)

    if os.path.exists(os.path.join('PowerLib', 'Mcu')):
        objects += add_component(env, ['PowerLib', 'Mcu'], False)

# -------------------------------------------------------------------------------------------------------
#   T_dir               = os.path.join(env.subst('$OUTPUT_DIR'))
#   T_path              = scons_common.create_work_dir(T_dir)
#   T_objs_file         = os.path.join(T_path, env.subst('$TARGET_NAME')) + ".objectlist"
#   T_objects_path      = scons_common.gen_link_objects_file(T_objs_file, objects)
#
#   env.Append(LINKCOM=' @'+ T_objects_path)
#   env.Append(LINKERGENMAPFILE= " -m31 > " + T_path + os.sep + env.subst('$TARGET_NAME') + ".map")
#   env.Append(LINKCMDFILE= env.subst('$LINKER_FILE'))
#   exe_dir = os.path.join(env.subst('$OUTPUT_DIR'), env.subst('$TARGET_NAME'))
# -------------------------------------------------------------------------------------------------------
    # Setup output path for debug, hex and A2L files
    out_path = os.path.join(env.subst('$OUTPUT_BINARY_DIR'),
                            env.subst('$TARGET_NAME'))
    # hex_path    = os.path.join(env.subst('$OUTPUT_BINARY_DIR'), 'hex', env.subst('$TARGET_NAME'))
    # s19_path    = os.path.join(env.subst('$OUTPUT_BINARY_DIR'), 's19', env.subst('$TARGET_NAME'))
    # mem_path    = os.path.join(env.subst('$OUTPUT_BINARY_DIR'), env.subst('$TARGET_NAME')+'.map')

    file1_path = os.path.join(env.subst('$LIBRARY_DIR'), "libMcalCdd.a")
    file2_path = os.path.join(env.subst('$LIBRARY_DIR'), "libPlatform.a")
    file3_path = os.path.join(env.subst('$LIBRARY_DIR'), "libService.a")
    file4_path = os.path.join(env.subst('$LIBRARY_DIR'), "libCommon.a")

    # Build final debug, elf
    out_exe = env.Program(out_path, objects, LIBS=[file1_path, file2_path, file3_path, file4_path])

    # Setup explicit dependency of elf file to linker script
    env.Depends(out_exe, env['LINKER_FILE'])
    # Setup explicit dependency of elf file to static library file of OS
    env.Depends(out_exe, env['LIBRARY_PATHS'])

    # hex_exe     = env.Hex(hex_path, out_exe)
    # s19_exe     = env.S19(s19_path, out_exe)

    # meminfo     = env.Meminfo(mem_path, out_exe)
    ############ END SCONSCRIPT ############

    ########## END SCONSTRUCT ##########
