import sys

from bento.commands import hooks

@hooks.pre_build
def pre_build(context):
    default_builder = context.default_builder
    bld = context.waf_context
    f2py = bld.tools["f2py"]

    def builder(extension):
        source = extension.sources[:]
        if sys.platform == "darwin":
            source.pop(source.index("src/fblaswrap.f"))
            source.append("src/fblaswrap_veclib_c.c")
        return default_builder(extension,
                               features="c fc pyext bento cshlib f2py",
                               source=source,
                               use="FBLAS")
    context.register_builder("fblas", builder)

    def builder(extension):
        t = default_builder(extension,
                            features="c pyext bento cshlib f2py",
                            use="CBLAS")
        t.mappings[".pyf"] = f2py.interface_gen_callback
        return t
    context.register_builder("cblas", builder)

    def builder(extension):
        t = default_builder(extension,
                            features="c pyext bento cshlib f2py",
                            use="FLAPACK")
        t.mappings[".pyf"] = f2py.interface_gen_callback
        return t
    context.register_builder("flapack", builder)

    def builder(extension):
        kw = {}
        if bld.env.HAS_CLAPACK:
            kw["use"] = "CLAPACK"
            kw["features"] = "c pyext bento cshlib f2py"
            interface_gen_callback = f2py.interface_gen_callback
        else:
            kw["features"] = "c fc pyext bento cshlib f2py"
            interface_gen_callback = f2py.fake_interface_gen_callback
        t = default_builder(extension, **kw)
        t.mappings[".pyf"] = interface_gen_callback
        return t
    context.register_builder("clapack", builder)

    context.register_builder("_flinalg",
                             lambda e: default_builder(e,
                                                       features="c pyext bento cshlib f2py f2py_fortran",
                                                       use="FLAPACK"))
    context.register_builder("calc_lwork",
                             lambda e: default_builder(e,
                                                       features="c pyext bento cshlib f2py f2py_fortran",
                                                       use="FLAPACK CLIB"))

    defines = []
    if bld.env.HAS_ATLAS:
        raise NotImplementedError("Atlas not implemented yet")
    else:
        defines.append("NO_ATLAS_INFO=1")
    context.register_builder("atlas_version", lambda e: default_builder(e, defines=defines))
