#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
setup.py file for @PYPACKAGE_NAME@

"""
from numpy.distutils.core import setup, Extension
from numpy.distutils.misc_util import Configuration
import os
import glob
import fnmatch

def parseCmakeVar(var):
    if var != "":
        return var.split(';')
    else:
        return None

def create_swig_extension(name, inc_dirs, src_dirs=None, sources=None):
    """Create a python module from C++ files, using swig
    """
    
    swig_dir  = os.path.join('@CMAKE_SOURCE_DIR@', 'swig')
    swig_config_file = os.path.join(swig_dir, name+'.i')

    include_dirs = set(inc_dirs)
    if sources is None:
        sources = []
        if(src_dirs == None):
            assert(inc_dirs != None)
            for idir in inc_dirs:
                #sources += glob.glob(os.path.join(idir, '**/*.cpp'), recursive=True)
                for root, dirnames, filenames in os.walk(idir):
                    for filename in fnmatch.filter(filenames, '*.cpp'):
                        sources.append(os.path.join(root, filename))

        else:
            for sdir in src_dirs:
                sources += glob.glob(os.path.join(sdir, '*.cpp'))
    else:
        for f in sources:
            include_dirs.add(os.path.dirname(f))

    sources.insert(0,swig_config_file)
    include_dirs = list(include_dirs)

    name = 'hysop._' + name
    swig_opts = ['-I' + swig_dir,
                 '-c++', '-modern']
                 #-outdir', '/Users/Franck/toto',
    
    extern_includes = parseCmakeVar("@CXX_EXT_INCLUDES@")
    if(extern_includes != None):
        for exti in extern_includes:
            include_dirs.append(exti)

    libraries = parseCmakeVar("@CXX_EXT_LIBS@")
    library_dirs = parseCmakeVar("@CXX_EXT_LIB_DIRS@")
    extra_compile_args = parseCmakeVar("@CXX_FLAGS@")
    extra_link_args = parseCmakeVar("@CXX_LINKER_FLAGS@")
    define_macros = parseCmakeVar("@CXX_EXTRA_DEFINES@")

    #print "INCLUDE_DIRS=",include_dirs
    #print "LIBRARIES=",libraries
    #print "LIBRARY_DIRS=",library_dirs
    #print "EXTRA_COMPILE_ARGS=",extra_compile_args
    #print "EXTRA_LINK_ARGS=",extra_link_args
    #print "DEFINE_MACROS=",define_macros
    #  To avoid -I -I in compiler call, which results in a bug:
    #while inc_dir.count('') > 0:
    #    inc_dir.remove('')
    #inc_dir.append('@CMAKE_BINARY_DIR@/Modules')
    
    swig_ext = Extension(name, sources=sources, language='c++',
                         swig_opts=swig_opts,
                         include_dirs=include_dirs,
                         library_dirs=library_dirs,
                         libraries=libraries,
                         define_macros=define_macros,
                         extra_compile_args=extra_compile_args,
                         extra_link_args=extra_link_args)

    return swig_ext


# Full package name
name = '@PYPACKAGE_NAME@'
# List of modules (directories) to be included
packages = ['hysop',
            'hysop.domain',
            'hysop.fields',
            'hysop.operator',
            'hysop.operator.discrete',
            'hysop.problem',
            'hysop.tools',
            'hysop.numerics',
            'hysop.numerics.integrators',
            ]

packages_for_tests = ['hysop.domain.tests',
                      'hysop.fields.tests',
                      'hysop.operator.tests',
                      'hysop.numerics.tests',
                      'hysop.tools.tests',
                      'hysop.problem.tests',
                      'hysop.numerics.tests',
                      ]

if "@USE_MPI@" is "ON":
    packages.append('hysop.mpi')
    packages_for_tests.append('hysop.mpi.tests')

if "@WITH_GPU@" is "ON":
    packages.append('hysop.gpu')
    packages_for_tests.append('hysop.gpu.tests')

if "@WITH_TESTS@" is "ON":
    packages = packages + packages_for_tests

# Enable this to get debug info
DISTUTILS_DEBUG = 1

ext_modules = []

# Check if libhysop was created
enable_fortran = "@WITH_LIB_FORTRAN@"


if enable_fortran is "ON":
    inc_dir = '@MPI_Fortran_INCLUDE_PATH@'.split(';')
    #  To avoid -I -I in compiler call. Result in a bug:
    while inc_dir.count('') > 0:
        inc_dir.remove('')

    hysop_dir = '@CMAKE_BINARY_DIR@/Modules'
    inc_dir.append(hysop_dir)
    fortran_dir = \
        '@CMAKE_SOURCE_DIR@/hysop/f2py/'
    hysop_libdir = ['@CMAKE_BINARY_DIR@/src']
    hysoplib = ['@HYSOP_LIBRARY_NAME@']
    f2py_options = ['--no-lower']
    fortran_src = []
    withfftw = "@WITH_FFTW@"
    if withfftw is "ON":
        fortran_src.append(fortran_dir + 'parameters.f90')
        fortran_src.append(fortran_dir + 'fftw2py.f90')
        fftwdir = '@FFTWLIB@'
        hysoplib.append('fftw3')
        hysoplib.append('fftw3_mpi')
        hysop_libdir.append(fftwdir)
    else:
        packages.append('hysop.fakef2py')
        packages.append('hysop.fakef2py.fftw2py')
    withscales = '@WITH_SCALES@'
    if withscales is "ON":
        if withfftw is "OFF":
            fortran_src.append(fortran_dir + 'parameters.f90')
        fortran_src.append(fortran_dir + 'scales2py.f90')
    else:
        packages.append('hysop.fakef2py')
        packages.append('hysop.fakef2py.scales2py')

    options = [('F2PY_REPORT_ON_ARRAY_COPY', '1')]
    if os.uname()[0] == 'Linux':
        options.append(('F2PY_REPORT_ATEXIT', '1'))

    parpyModule = Extension(name='hysop.f2py',
                            f2py_options=f2py_options,
                            sources=fortran_src,
                            include_dirs=inc_dir,
                            library_dirs=hysop_libdir,
                            libraries=hysoplib,
                            define_macros=options
                            )
    ext_modules.append(parpyModule)
else:
    packages.append('hysop.fakef2py')
    packages.append('hysop.fakef2py.scales2py')
    packages.append('hysop.fakef2py.fftw2py')

data_files = []

# --- C++ files and swig interface --
# path to .i files
swig_include_dirs = [os.path.join('@CMAKE_SOURCE_DIR@','swig')]

# C++ files and swig interface
cpp_include_dirs = ['src/fftw','src/hysop++/src']
for id in cpp_include_dirs:
    swig_include_dirs.append(os.path.join('@CMAKE_SOURCE_DIR@', id))

ext = {}
cpp2hysop = "@CPP_2_HYSOP@"
ext[cpp2hysop] = create_swig_extension(name=cpp2hysop, inc_dirs=swig_include_dirs)
for ex in ext:
    ext_modules.append(ext[ex])


if "@WITH_GPU@" is "ON":
    cl_src_dirs = ["cl_src", "cl_src/kernels",
                   "cl_src/advection", "cl_src/remeshing"]
    for cl_dir in cl_src_dirs:
        data_files.append(
            ('./hysop/gpu/' + cl_dir,
             ['@CMAKE_SOURCE_DIR@/hysop/gpu/' + cl_dir + '/'
              + cl_file
              for cl_file in os.listdir(
                  '@CMAKE_SOURCE_DIR@/hysop/gpu/' + cl_dir + '/')
              if cl_file[0] != '.' and cl_file[0] != '#' and cl_file[-3:] == '.cl']))

descr = 'Hybrid Computation with Particles.'
authors = 'G.H Cottet, J.M Etancelin, J.B Keck, C.Mimeau, F.Pérignon, C. Picard'
# authors = 'HySoP development team'
config = Configuration(
    name=name,
    version='@PYPACKAGE_VERSION@',
    description=descr,
    author=authors,
    author_email='hysop-members@lists.forge.imag.fr',
    url='https://forge.imag.fr/projects/hysop/',
    license='GNU public license',
    package_dir={'': '@CMAKE_SOURCE_DIR@'},
    ext_modules=ext_modules,
    packages=packages,
    data_files=data_files,
)

setup(**config.todict())
