#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import SCons
import shutil

Import('build')


# On Posix default SCons.LIBPREFIX = 'lib', on Windows default SCons.LIBPREFIX = ''

m4a_sources = [
    "soundsourcem4a.cpp",
    "sources/audiosource.cpp",
    "sources/metadatasourcetaglib.cpp",
    "sources/soundsource.cpp",
    "sources/soundsourceplugin.cpp",
    "util/audiosignal.cpp",
    "util/samplebuffer.cpp",
    "util/readaheadsamplebuffer.cpp",
    "util/sample.cpp",
    "util/logger.cpp",
    "util/indexrange.cpp",
    "track/albuminfo.cpp",
    "track/trackinfo.cpp",
    "track/trackmetadata.cpp",
    "track/trackmetadatataglib.cpp",
    "track/tracknumbers.cpp",
    "track/replaygain.cpp",
    "track/bpm.cpp"
]

#Tell SCons to build the SoundSourceM4A plugin
#=========================
if int(build.flags['faad']):
    env = build.env.Clone()

    conf = Configure(env)

    have_mp4v2_h = conf.CheckHeader('mp4v2/mp4v2.h')
    if have_mp4v2_h:
        env.Append(CPPDEFINES = '__MP4V2__')

    have_mp4 = conf.CheckLib(['mp4v2', 'libmp4v2']) or \
        conf.CheckLib('mp4')

    have_faad = conf.CheckLib(['faad', 'libfaad'])
    # We have to check for libfaad version 2.6 or 2.7. In libfaad
    # version 2.7, the type for the samplerate is unsigned long*,
    # while in 2.6 the type is uint32_t*. We can use the optional
    # call parameter to CheckLibWithHeader to build a test file to
    # check which one this faad.h supports.
    # This check doesn't work correctly on Windows and we build it
    # manually anyway, so we know it's v2.7.
    if have_faad and not build.platform_is_windows:
        have_faad_27_or_newer = conf.CheckLibWithHeader(
                'libfaad', 'neaacdec.h', 'c++',
                call = 'NeAACDecInit2(0, 0, 0, (unsigned long*)0, (unsigned char*)0);',
                autoadd=False)
        # Only the second check succeeds!! BUT WHY??
        # See also: https://stackoverflow.com/questions/26245218/how-to-clear-scons-cache-checklibwithheader-returns-no-first-time-called-ye
        have_faad_27_or_newer = conf.CheckLibWithHeader(
                'libfaad', 'neaacdec.h', 'c++',
                call = 'NeAACDecInit2(0, 0, 0, (unsigned long*)0, (unsigned char*)0);',
                autoadd=False)
        if not have_faad_27_or_newer:
            env.Append(CPPDEFINES = '__M4AHACK__')
            print("libfaad 2.6 compatibility mode... enabled")

    env = conf.Finish()
    results = []
    SHLIBPREFIX='lib' #Makes the filename "libsoundsourcem4a" consistently across platforms to make our lives easier.
    if build.platform_is_windows:
        env["LINKFLAGS"].remove("/entry:mainCRTStartup")
        # TODO(rryan): Why do we do this?
        if build.machine_is_64bit:
            env["LINKFLAGS"].remove("/subsystem:windows,5.02")
        else:
            env["LINKFLAGS"].remove("/subsystem:windows,5.01")
        ssm4a_bin = env.SharedLibrary('soundsourcem4a', m4a_sources, LINKCOM  = [env['LINKCOM'], 'mt.exe -nologo -manifest ${TARGET}.manifest -outputresource:$TARGET;1'])
        results.append('ssm4a_bin')
        if build.bundle_pdbs:
            ssm4a_pdb = env.SideEffect('soundsourcem4a.pdb', ssm4a_bin)
            results.append('ssm4a_pdb')
    else:
        ssm4a_bin = env.SharedLibrary('soundsourcem4a', m4a_sources)
        results.append('ssm4a_bin')

    #Pass this soundsourcem4a library object file back to the SConscript above us.
    Return(results)
else:
    Return("")
