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

# ####################################################################
#  Copyright (C) 2005-2013 by the FIFE team
#  http://www.fifengine.net
#  This file is part of FIFE.
#
#  FIFE is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public
#  License as published by the Free Software Foundation; either
#  version 2.1 of the License, or (at your option) any later version.
#
#  This library is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public
#  License along with this library; if not, write to the
#  Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
# ####################################################################

import os,sys
import utils.scons.scons_utils as utils
from utils.util_scripts.path import path as upath
import utils.scons.scons_builders as builders

Import('env', 'opts')

_sep = os.path.sep
src_path = upath(opts['SRC'])
engine_path = opts['SRC']
core_path = os.path.join('engine', 'core')
extensionpath = upath(os.path.join(opts['SRC'], 'python', 'fife', 'extensions'))

local_tinyxml = env['LOCAL_TINYXML']
fifechan = env['ENABLE_FIFECHAN']
librocket = env['ENABLE_LIBROCKET']
cegui = env['ENABLE_CEGUI']

if fifechan:
	Import('fifechan_env')

#**************************************************************************
#Compile the list of source code to be used
#**************************************************************************
dirfilters = ['swigwrappers', 'tinyxml', 'fifechan', 'librocket', 'cegui']

allfiles = list(src_path.walkfiles())
allfiles_base = list()
for f in allfiles:
	allfiles_base.append(utils.relpath(f, opts['SRC']))

extpyfiles = list(extensionpath.walkfiles('*.py'))
extensionfiles = list()
relextensionfiles = list()
for f in extpyfiles:
	extensionfiles.append(utils.relpath(f, opts['SRC']))
	relextensionfiles.append(utils.relpath(f, os.path.join(opts['SRC'], 'python', 'fife')))
	
headerfiles = [f for f in allfiles_base if utils.is_headerfile(f)]
implfiles = [f for f in allfiles_base if utils.is_implfile(f)]
swigfiles = [f for f in allfiles_base if utils.is_swigfile(f)]
intfiles = utils.filter_by_dir(dirfilters, swigfiles)
compilefiles = utils.filter_by_dir(dirfilters, implfiles)
headerfiles = utils.filter_by_dir(['tinyxml', 'fifechan'], headerfiles)
fife_imports = []

if sys.platform == 'win32':
	dllpath = upath(opts['DLLPATH'])
	dllfilelist = list(dllpath.walkfiles('*.dll'))
	dllfiles = list()
	for f in dllfilelist:
		dllfiles.append(utils.relpath(f,opts['DLLPATH']))

#**************************************************************************
# if --local-tinyxml is defined or the system version is not found then
# add the local tinyxml header/impl files to the overall compile list
#**************************************************************************
if (local_tinyxml):
	# get all files in ext/tinyxml directory
	local_tinyxml_files = utils.include_by_dir(['tinyxml'], allfiles_base) 
	
	#filter header files and add to overall list
	local_tinyxml_headerfiles = [f for f in local_tinyxml_files if utils.is_headerfile(f)]
	headerfiles = headerfiles + local_tinyxml_headerfiles
	
	# filter impl files and add to overall list
	local_tinyxml_implfiles = [f for f in local_tinyxml_files if utils.is_implfile(f)]
	compilefiles = compilefiles + local_tinyxml_implfiles

#**************************************************************************
# Compile the list of fifechan glue code
#**************************************************************************
fifechan_glue_headerfiles = utils.include_by_dir(['fifechan'], headerfiles)
fifechan_glue_implfiles = utils.include_by_dir(['fifechan'], implfiles)
fifechan_glue_swigfiles = utils.include_by_dir(['fifechan'], swigfiles)

fifechan_lib_swigfiles = utils.include_by_dir(['lib'], fifechan_glue_swigfiles)

fifechan_glue_swigfiles = list(set(fifechan_glue_swigfiles).difference(set(fifechan_lib_swigfiles)))

#if fifechan is enabled add fifechan glue source code to all source code
if fifechan:
	headerfiles = headerfiles + fifechan_glue_headerfiles
	compilefiles = compilefiles + fifechan_glue_implfiles 
	
#**************************************************************************
# Compile the list of rocket glue code
#**************************************************************************
rocket_glue_headerfiles = utils.include_by_dir(['librocket'], headerfiles)
rocket_glue_implfiles = utils.include_by_dir(['librocket'], implfiles)
rocket_glue_swigfiles = utils.include_by_dir(['librocket'], swigfiles)

if librocket:
	headerfiles = headerfiles + rocket_glue_headerfiles
	compilefiles = compilefiles + rocket_glue_implfiles

#**************************************************************************
# Compile the list of cegui glue code
#**************************************************************************

cegui_glue_headerfiles = utils.include_by_dir(['cegui'], headerfiles)
cegui_glue_implfiles = utils.include_by_dir(['cegui'], implfiles)
cegui_glue_swigfiles = utils.include_by_dir(['cegui'], swigfiles)

if cegui:
	headerfiles = headerfiles + cegui_glue_headerfiles
	compilefiles = compilefiles + cegui_glue_implfiles

#**************************************************************************
# define the FIFE git hash number
#
# only define this if a valid hash was detected
#**************************************************************************
if opts['FIFE_GIT_HASH']:
	if opts['FIFE_GIT_HASH'] is not "":
		env.AppendUnique(CPPDEFINES = ['FIFE_GIT_HASH=' + opts['FIFE_GIT_HASH']])	

#**************************************************************************
# python
#**************************************************************************

#if fifechan is enabled 
if fifechan:
	#add interface files with fifechan glue code to the standard fife module 
	intfiles = intfiles + fifechan_glue_swigfiles

	#generate swig interface file for fifechan module
	utils.gen_swig_interface(os.path.join(engine_path, 'swigwrappers', 'python', 'fifechan.i.templ'), 
										fifechan_lib_swigfiles,
										os.path.join(engine_path, 'swigwrappers', 'python'),
										'fifechan.i')
	fife_imports.append(os.path.join('swigwrappers', 'python', 'fifechan.i'))
	fifechan_pyfiles = [os.path.join('swigwrappers', 'python', 'fifechan_wrap.cc')]

#if librocket is enabled
if librocket:
	intfiles = intfiles + rocket_glue_swigfiles
	
if cegui:
	intfiles = intfiles + cegui_glue_swigfiles

	
#generate swig interface file for fife module
utils.gen_swig_interface(os.path.join(engine_path, 'swigwrappers', 'python', 'fife.i.templ'), 
										intfiles,
										os.path.join(engine_path, 'swigwrappers', 'python'),
										'fife.i',
										fife_imports)

pyfiles = list(compilefiles)
pyfiles.append([os.path.join('swigwrappers', 'python' ,'fife_wrap.cc')])


#**************************************************************************
#definition of scons builders for project files
#**************************************************************************

msvc_project_builder = Builder(action = builders.generate_msvc_project, suffix = '.vcproj')
env.Append(BUILDERS = {'MSVCProject': msvc_project_builder})

msvc_project_builder9 = Builder(action = builders.generate_msvc_project9, suffix = '.vcproj')
env.Append(BUILDERS = {'MSVCProject9': msvc_project_builder9})

codeblocks_project_builder_win32 = Builder(action = builders.generate_codeblocks_project_win32, suffix = '.cbp')
env.Append(BUILDERS = {'CodeblocksProjectWin32': codeblocks_project_builder_win32})

codeblocks_project_builder_linux = Builder(action = builders.generate_codeblocks_project_linux, suffix = '.cbp')
env.Append(BUILDERS = {'CodeblocksProjectLinux': codeblocks_project_builder_linux})

python_extensions_builder = Builder(action = "$SWIG -o $TARGET ${_SWIGOUTDIR} ${_SWIGINCFLAGS} $SWIGFLAGS $SOURCES")
env.Append(BUILDERS = {'PythonExtensions': python_extensions_builder})
if fifechan:
	fifechan_env.Append(BUILDERS = { 'PythonExtensions': python_extensions_builder})


#**************************************************************************
#project files target
#**************************************************************************

projectfiles = compilefiles + headerfiles
#projectfiles.append('swigwrappers/python/fife_wrap.cc')

msvcproj = env.MSVCProject(os.path.join('..', '..','..', builders.msvcbuildpath, 'fife'), projectfiles)
msvcproj9 = env.MSVCProject9(os.path.join('..', '..','..', builders.msvcbuildpath9, 'fife'), projectfiles)
cbproj_win32 = env.CodeblocksProjectWin32(os.path.join('..', '..','..', builders.cbbuildpath_win32, 'fife'), projectfiles)
cbproj_linux = env.CodeblocksProjectLinux(os.path.join('..', '..','..', builders.cbbuildpath_linux, 'fife'), projectfiles)


if opts['DEBUG'] and sys.platform == 'win32':
	fife_tgt = 'fife_d'
else:
	fife_tgt = 'fife'


#**************************************************************************
#shared library target
#**************************************************************************

if sys.platform == 'win32':
	env.AppendUnique(CPPDEFINES = ['FIFE_EXPORTING'])
	sharedlib = env.SharedLibrary(target = fife_tgt,
								  source = compilefiles,
								  OBJPREFIX='shared_',
								  SHLIBEMITTER = '')
elif sys.platform == 'darwin':
	sharedlib = env.SharedLibrary(target = fife_tgt,
								  source = compilefiles)
elif sys.platform.startswith('openbsd'):
	soname = env.subst('$SHLIBPREFIX') + fife_tgt + env.subst('$SHLIBSUFFIX')
	sharedlib = env.SharedLibrary(target = fife_tgt,
								  source = compilefiles,
								  SHLIBSUFFIX = env.subst('$SHLIBSUFFIX'),
								  LINKFLAGS=['-Wl,-soname,' + str(soname)])
else:
	# soname will be libfife.so.major
	majorVersion = opts['FIFE_VERSION'].split('.')[0]	
	soname = env.subst('$SHLIBPREFIX') + fife_tgt + env.subst('$SHLIBSUFFIX') + '.' + majorVersion
	sharedlib = env.SharedLibrary(target = fife_tgt,
								  source = compilefiles,
								  SHLIBSUFFIX = env.subst('$SHLIBSUFFIX') + '.' + opts['FIFE_VERSION'],
								  LINKFLAGS=['-Wl,-soname,' + str(soname)])

#**************************************************************************
#python library target
#**************************************************************************
if sys.platform == 'win32':
	dest_suffix = '.pyd'
else:
	dest_suffix = '.so'
	
pythonlib = env.SharedLibrary(target = fife_tgt,
							  source = pyfiles,
							  OBJPREFIX='py_',
							  SHLIBPREFIX='_',
							  SHLIBSUFFIX=dest_suffix,
							  SHLIBEMITTER = '')

pythonext = env.PythonExtensions(target = [os.path.join('swigwrappers', 'python' ,'fife_wrap.cc'),
										   os.path.join('swigwrappers', 'python' ,'fife_wrap.h'),
										   os.path.join('python', 'fife', 'fife.py')],
							  source = os.path.join('swigwrappers', 'python' ,'fife.i'),
							  SWIGFLAGS=['-python','-c++','-w511', '-w473', '-w404'],
							  SWIGPATH='core',
							  SWIGOUTDIR=Dir('#/engine/python/fife').srcnode().path)

if opts['DEBUG'] and sys.platform == 'win32':
	copy_dest = os.path.join(opts['PYLIB_COPY_DEST'], '_fife_d' + dest_suffix)
else:
	copy_dest = os.path.join(opts['PYLIB_COPY_DEST'], '_fife' + dest_suffix)

copy_cmd = env.Command(copy_dest, pythonlib, [Copy('$TARGET', '$SOURCE')])
copy_cmd2 = env.Command(os.path.join(opts['WRAP_COPY_DEST'], 'fife_wrap.h'),
				os.path.join('swigwrappers','python','fife_wrap.h'),
				[Copy('$TARGET', '$SOURCE')])
copy_cmd3 = env.Command(os.path.join(opts['WRAP_COPY_DEST'], 'fife_wrap.cc'),
				os.path.join('swigwrappers','python','fife_wrap.cc'),
				[Copy('$TARGET', '$SOURCE')])

if fifechan:
	fifechan_lib_env = fifechan_env

	fifechan_pythonlib = fifechan_lib_env.SharedLibrary(target = 'fifechan',
												source = fifechan_pyfiles,
												OBJPREFIX='py_',
												SHLIBPREFIX='_',
												SHLIBSUFFIX=dest_suffix,
												SHLIBEMITTER = '')
												
	fifechan_pythonext = fifechan_lib_env.PythonExtensions(target = [os.path.join('swigwrappers', 'python' ,'fifechan_wrap.cc'),
																	os.path.join('swigwrappers', 'python' ,'fifechan_wrap.h'),
																	os.path.join('python', 'fife', 'fifechan.py')],
																	source = os.path.join('swigwrappers', 'python' ,'fifechan.i'),
																	SWIGFLAGS=['-python','-c++','-w511'],
																	SWIGPATH='core',
																	SWIGOUTDIR=Dir('#/engine/python/fife').srcnode().path)
	if opts['DEBUG'] and sys.platform == 'win32':
		copy_dest = os.path.join(opts['PYLIB_COPY_DEST'], '_fifechan_d' + dest_suffix)
	else:
		copy_dest = os.path.join(opts['PYLIB_COPY_DEST'], '_fifechan' + dest_suffix)

	copy_fcn_cmd = env.Command(copy_dest, fifechan_pythonlib, [Copy('$TARGET', '$SOURCE')])
	copy_fcn_cmd2 = env.Command(os.path.join(opts['WRAP_COPY_DEST'], 'fifechan_wrap.h'),
								os.path.join('swigwrappers','python','fifechan_wrap.h'),
								[Copy('$TARGET', '$SOURCE')])
	copy_fcn_cmd3 = env.Command(os.path.join(opts['WRAP_COPY_DEST'], 'fifechan_wrap.cc'),
								os.path.join('swigwrappers','python','fifechan_wrap.cc'),
								[Copy('$TARGET', '$SOURCE')])

#**************************************************************************
#static library target
#**************************************************************************

staticlib = env.StaticLibrary(target = fife_tgt,
							  source = compilefiles,
							  LINKFLAGS=['-Wl'])

#**************************************************************************
#Install targets
#**************************************************************************

#TODO: This is not complete.  Because of the current linux rpath issue this
#will not work as expected.
install_static = env.Install(opts['LIBDIR'], staticlib)
install_shared = env.Install(opts['LIBDIR'], sharedlib)

headerdestlist = utils.gen_dest_files(os.path.join(opts['PREFIX'], 'include', 'fife'), headerfiles)
install_headers = env.InstallAs(headerdestlist, headerfiles)

pypath = os.path.join(opts['PYTHON_PREFIX'], 'fife') 
extdestfilelist = utils.gen_dest_files(pypath, relextensionfiles)

install_python_lib = env.Install(pypath, pythonlib)
install_python_module = env.Install(pypath, ['#/engine/python/fife/fife.py','#/engine/python/fife/__init__.py'])
if fifechan:
	install_python_lib.append(env.Install(pypath, fifechan_pythonlib))
	install_python_module.append(env.Install(pypath, '#/engine/python/fife/fifechan.py'))
install_python_extensions = env.InstallAs(extdestfilelist, extensionfiles)

if sys.platform == 'win32':
	dlldestfilelist = utils.gen_dest_files(pypath, dllfiles)
	dlldestfilelist2 = utils.gen_dest_files(os.path.join(engine_path, 'python', 'fife'), dllfiles)
	
	install_dlls = env.InstallAs(dlldestfilelist, dllfilelist)
	install_dlls2 = env.InstallAs(dlldestfilelist2, dllfilelist)

#**************************************************************************
#alias definitions
#**************************************************************************

alias_msvc = Alias('msvc',msvcproj)
alias_msvc9 = Alias('msvc9',msvcproj9)
alias_cbwin32 = Alias('cbwin32',cbproj_win32)
alias_cblinux = Alias('cblinux',cbproj_linux)
Alias('projects',[alias_msvc, alias_msvc9, alias_cbwin32, alias_cblinux])

alias_shared = Alias('fife-shared', sharedlib)
alias_static = Alias('fife-static', staticlib)

alias_swig_commands = [pythonext, copy_cmd2, copy_cmd3]
if fifechan:
	alias_swig_commands = alias_swig_commands + [fifechan_pythonext, copy_fcn_cmd2, copy_fcn_cmd3]

alias_swig = Alias('fife-swig', alias_swig_commands)

alias_python_commands = [pythonlib, copy_cmd, alias_swig]
if fifechan:
	alias_python_commands = [fifechan_pythonlib, copy_fcn_cmd] + alias_python_commands
	
if sys.platform == 'win32':
	alias_python_commands.append(install_dlls2)

alias_python = Alias('fife-python', alias_python_commands)
	
Alias('fife', [alias_shared, alias_static, alias_python])
alias_install_shared = Alias('install-shared', install_shared)
alias_install_static = Alias('install-static', install_static)

if sys.platform == 'win32':
	alias_install_python = Alias('install-python', [alias_python, install_python_lib, install_python_module, install_python_extensions, install_dlls]) 
else:
	alias_install_python = Alias('install-python', [alias_python, install_python_lib, install_python_module, install_python_extensions])
	
alias_install_dev = Alias('install-dev', [alias_install_shared, alias_install_static, install_headers])
Alias('install-all', [alias_install_python, alias_install_dev])

# vim: set filetype=python:
