from os.path import join as pjoin
import os
from buildutils import *

Import('env', 'build', 'install', 'buildSample')

# (subdir, program name, [source extensions], openmp_flag)
samples = [
    ('combustor', 'combustor', ['cpp'], False),
    ('custom', 'custom', ['cpp'], False),
    ('demo', 'demo', ['cpp'], False),
    ('flamespeed', 'flamespeed', ['cpp'], False),
    ('kinetics1', 'kinetics1', ['cpp'], False),
    ('jacobian', 'derivative_speed', ['cpp'], False),
    ('gas_transport', 'gas_transport', ['cpp'], False),
    ('rankine', 'rankine', ['cpp'], False),
    ('LiC6_electrode', 'LiC6_electrode', ['cpp'], False),
    ('openmp_ignition', 'openmp_ignition', ['cpp'], True),
    ('bvp', 'blasius', ['cpp'], False)
]

for subdir, name, extensions, openmp in samples:
    localenv = env.Clone()
    if openmp:
        localenv.Append(CXXFLAGS=env['openmp_flag'], LINKFLAGS=env['openmp_flag'])
        if env['using_apple_clang']:
            localenv.Append(LIBS=['omp'])

        localenv['cmake_extra'] = """
find_package(OpenMP REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
"""
    else:
        localenv['cmake_extra'] = ''

    # TODO: Accelerate is only used if other BLAS/LAPACK are not used
    if env["OS"] == "Darwin":
        localenv["cmake_extra"] += "find_library(ACCELERATE_FRAMEWORK Accelerate)"
        localenv.Append(
            LINKFLAGS=env.subst("${RPATHPREFIX}${ct_libdir}${RPATHSUFFIX}"))

    localenv.Append(LIBS=env['cantera_shared_libs'])
    localenv.Prepend(CPPPATH=['#include'])

    if openmp and not env['HAS_OPENMP']:
        logger.info(f"Skipping sample {name!r} because 'omp.h' was not found.")
    else:
        buildSample(localenv.Program, pjoin(subdir, name),
                    multi_glob(localenv, subdir, *extensions))

    # Note: These CMakeLists.txt and SConstruct files are automatically installed
    # by the "RecursiveInstall" that grabs everything in the cxx directory.

    flag_excludes = [r"\$\(", "/TP", r"\$\)", "/nologo"]
    incdirs = [localenv["ct_incroot"]]
    libdirs = [localenv["ct_libdir"]]
    if localenv["package_build"]:
        # Remove sysroot flags in templated output files. This only applies to the
        # conda package for now.
        # Users should compile against their local SDKs, which should be backwards
        # compatible with the SDK used for building.
        flag_excludes.extend(["-isysroot", "-mmacosx", "-march", "-mtune",
                              "-fdebug-prefix-map", ".*/_build_env/"])
    else:
        incdirs.extend([localenv["sundials_include"], localenv["boost_inc_dir"]])
        incdirs.append(localenv["hdf_include"])
        incdirs.extend(localenv["extra_inc_dirs"])
        incdirs = list(set(incdirs))

        libdirs.extend(localenv["extra_lib_dirs"])
        libdirs = list(set(libdirs))

    if env["OS"] == "Darwin" and env["use_rpath_linkage"] and not env.subst("$__RPATH"):
        # SCons fails to specify RPATH on macOS, so circumvent that behavior by
        # specifying this directly as part of LINKFLAGS
        localenv.Append(LINKFLAGS=[env.subst(f'$RPATHPREFIX{d}$RPATHSUFFIX')
                                   for d in libdirs])

    cc_flags = compiler_flag_list(localenv["CCFLAGS"] + localenv["CXXFLAGS"],
                                  env["CC"], flag_excludes)
    link_flags = compiler_flag_list(localenv["LINKFLAGS"], env["CC"], flag_excludes)
    localenv["tmpl_compiler_flags"] = repr(cc_flags)
    localenv['tmpl_cantera_frameworks'] = repr(localenv['FRAMEWORKS'])
    localenv['tmpl_cantera_incdirs'] = repr([x for x in incdirs if x])
    localenv['cmake_cantera_incdirs'] = ' '.join(quoted(x) for x in incdirs if x)
    localenv['tmpl_cantera_libs'] = repr(localenv['cantera_shared_libs'])
    localenv['cmake_cantera_libs'] = ' '.join(localenv['cantera_shared_libs'])
    if env['OS'] == 'Darwin':
        localenv['cmake_cantera_libs'] += ' ${ACCELERATE_FRAMEWORK}'
        localenv['cmake_cantera_incdirs'] += ' "/usr/local/include"'
    localenv['tmpl_cantera_libdirs'] = repr([x for x in libdirs if x])
    localenv['cmake_cantera_libdirs'] = ' '.join(quoted(x) for x in libdirs if x)
    localenv['tmpl_cantera_linkflags'] = repr(link_flags)
    localenv['tmpl_progname'] = name
    localenv['tmpl_sourcename'] = name + '.cpp'
    env_args = []

    ## Generate SConstruct files to be installed
    if localenv['TARGET_ARCH'] is not None:
        env_args.append('TARGET_ARCH={0!r}'.format(localenv['TARGET_ARCH']))
    if 'MSVC_VERSION' in localenv:
        env_args.append('MSVC_VERSION={0!r}'.format(localenv['MSVC_VERSION']))
    localenv['tmpl_env_args'] = ', '.join(env_args)

    if localenv['package_build']:
        # For package builds, use environment variables or rely on SCons to find the
        # default compiler
        localenv['tmpl_cxx'] = "env['CXX'] = os.environ.get('CXX', env['CXX'])"
    else:
        # Otherwise, use the same compiler that was used to build Cantera, with the
        # environment variables optionally overriding
        localenv['tmpl_cxx'] = env.subst("env['CXX'] = os.environ.get('CXX', '$CXX')")

    sconstruct = localenv.SubstFile(pjoin(subdir, 'SConstruct'), 'SConstruct.in')
    install(pjoin('$inst_sampledir', 'cxx', subdir), sconstruct)

    ## Generate CMakeList.txt files to be installed
    cmakelists = localenv.SubstFile(pjoin(subdir, 'CMakeLists.txt'), 'CMakeLists.txt.in')
    install(pjoin('$inst_sampledir', 'cxx', subdir), cmakelists)
