import sys
import os

from bento.commands import hooks
from scipy._build_utils import get_g77_abi_wrappers

@hooks.pre_build
def pre_build(context):
    default_builder = context.default_builder
    bld = context.waf_context

    def fblas_builder(extension):
        source = extension.sources[:]

        # XXX: detect this properly
        if sys.platform == "darwin":
            info = {'extra_link_args': 'Accelerate'}
        else:
            info = {}
	source += [os.path.relpath(f, os.path.abspath(os.path.dirname(__file__)))
                   for f in get_g77_abi_wrappers(info)]

        return default_builder(extension,
                               features="c fc pyext bento cshlib f2py",
                               source=source,
                               use="LAPACK CLIB")
    context.register_builder("_fblas", fblas_builder)

    def cblas_builder(extension):
        if bld.env.HAS_CBLAS:
            return default_builder(extension,
                                   features="c fc pyext bento cshlib f2py",
                                   use="CBLAS")
    context.register_builder("_cblas", cblas_builder)

    def flapack_builder(extension):
        source = extension.sources[:]

        # XXX: detect this properly
        if sys.platform == "darwin":
            info = {'extra_link_args': 'Accelerate'}
        else:
            info = {}
	source += [os.path.relpath(f, os.path.abspath(os.path.dirname(__file__)))
                   for f in get_g77_abi_wrappers(info)]

        return default_builder(extension,
                               features="c fc pyext bento cshlib f2py",
                               source=source,
                               use="LAPACK CLIB")
    context.register_builder("_flapack", flapack_builder)

    def clapack_builder(extension):
        if bld.env.HAS_CLAPACK:
            return default_builder(extension,
                                   features="c pyext bento cshlib f2py",
                                   use="CLAPACK")
    context.register_builder("_clapack", clapack_builder)

    context.tweak_extension("_flinalg",
                            features="c fc pyext bento cshlib f2py f2py_fortran",
                            use="LAPACK CLIB")
    context.tweak_extension("calc_lwork",
                            features="c fc pyext bento cshlib f2py f2py_fortran",
                            use="LAPACK CLIB")
    context.tweak_extension("_interpolative",
                            features="c fc pyext bento cshlib f2py",
                            use="LAPACK CLIB")
