#!/usr/bin/python

from cffi import FFI
import os
import sys
import subprocess as sb
import platform

ffibuilder = FFI()

sources = [
    'lib/KNT_qhull.c',
    'lib/KNT_closures.c',
    'lib/KNT_lib.c',
    'lib/KNT_io.c',
    'lib/KNT_simplify.c',
    'lib/KNT_identify.c',
    'lib/KNT_arc.c',
    'KymoKnot_bindings.c',
    'lib/Alexander.c',
    'KNTclose.c',
    'lib/KNT_manager.c',
    'lib/my_geom.c',
    'lib/messages.c',
    'lib/prng.c',
    'lib/my_memory.c'
]


c_header_source = (
"""
#include "KymoKnot_bindings.h"
"""
)

platsys = platform.system()

# change also MANIFEST.in!
include_dirs = ["./include"]

libraries = ['m']
extra_objects = []


try:

    prefix = os.environ.get("QHULL_PREFIX")

    if prefix is None:

        prefix = sb.check_output(["pkg-config", "--variable=prefix", "qhullstatic"])
        prefix = prefix.decode("utf-8")
        prefix = prefix.strip()

        include_dirs.append(os.path.join(prefix, "include", "libqhull"))

        if platsys == "Darwin":
            extra_objects.append(os.path.join(prefix, "lib", "libqhullstatic.a"))

        elif platsys == "Linux":
            libraries.append("qhull")

    else:
        include_dirs.append(os.path.join(prefix, "include", "libqhull"))
        extra_objects.append(os.path.join(prefix, "lib", "libqhullstatic.a"))
        #libraries.append("qhull")


except Exception as e:
    print("")
    print("Cannot use pkg-config")
    print("Exception: {}".format(e))
    print("")

    if platsys == "Darwin":
        include_dirs.append("/usr/local/Cellar/qhull/2020.2/include/libqhull")
        extra_objects.append("/usr/local/Cellar/qhull/2020.2/lib/libqhullstatic.a")

    elif platsys == "Linux":
        libraries.append("qhull")

    elif platsys == "Windows":
        pass


ffibuilder.set_source(
    "_kymoknot_bindings",
    c_header_source,
    sources=sources,

    #Not working for packaging, I still rely in MANIFEST.in to get headers
    include_dirs=include_dirs,

    libraries=libraries,

    extra_objects=extra_objects,

    #DO NOT remove these flags during development,
    extra_compile_args=["-Werror-implicit-function-declaration", "-Werror=incompatible-pointer-types"],
)


#
# c_exports.h are the interfaces exported by the module
# To generate c_exports from cli:
# $ cd kymoknot-devel
# $ gcc -E ../include/KymoKnot_bindings.h > kymoknot/c_exports.h
#
# during development, c_exports.h is generated by calling this script with the dev parameter
#

fd = open("kymoknot/c_exports.h", "r", encoding="utf-8")
c_exports = fd.read()
fd.close()


if __name__ == "__main__":

    if len(sys.argv) > 1 and sys.argv[1] == "dev":

        c_exports = sb.check_output(["gcc -E include/KymoKnot_bindings.h"], shell=True)
        c_exports = c_exports.decode("utf-8")

        fd = open("kymoknot/c_exports.h", "w", encoding="utf-8")
        fd.write(c_exports)
        fd.close()

    ffibuilder.cdef(c_exports)
    ffibuilder.compile(verbose=True)

else:
    ffibuilder.cdef(c_exports)

