import os
import sys
import subprocess
import glob

from setuptools import setup
from setuptools.extension import Extension
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext

class CMakeExtension(Extension):
    def __init__(self, name, sourcedir=''):
        src = glob.glob('src/*')
        src.append('gdconfig.hpp.in')
        src.append('CMakeLists.txt')
        Extension.__init__(self, name, sources=src)
        self.sourcedir = os.path.abspath(sourcedir)

class CMakeBuild(build_ext):
    
    def run(self):
        try:
            subprocess.check_output(['cmake', '--version'])
        except OSError:
            raise RuntimeError("CMake must be installed to build the following extensions: " +
                               ", ".join(e.name for e in self.extensions))
        for ext in self.extensions:
            self.build_extension(ext)

    def build_extension(self, ext):

        extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name)))

        cmake_args = ['-DPYTHON_EXECUTABLE=' + sys.executable,
                      '-DBUILD_PYGDICHOTOMY=ON',
                      '-DPYGDICHOTOMY_RELEASE='+extdir]

        cfg = 'Debug' if self.debug else 'Release'
        build_args = ['--config', cfg]
        build_args += ['--', '-j{}'.format(os.cpu_count())]

        env = os.environ.copy()
        env['CXXFLAGS'] = '{} -DVERSION_INFO=\\"{}\\"'.format(env.get('CXXFLAGS', ''), self.distribution.get_version())

        if not os.path.exists(self.build_temp):
            os.makedirs(self.build_temp)

        subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp, env=env)

        subprocess.check_call(['cmake', '--build', '.', '-t', 'pygdichotomy'] + build_args, cwd=self.build_temp)

setup(
    name='pygeneraldichotomy',
    version="0.0.1.4", # hash 4c41f8da6ba21970dc503ee1668717f472a5521a 
    packages=["pygeneraldichotomy"],
    package_dir={"pygeneraldichotomy": "pygeneraldichotomy"},
    long_description=open("README.md").read(),
    long_description_content_type='text/markdown',
    ext_modules=[CMakeExtension('pygeneraldichotomy.libpygdichotomy')],
    cmdclass=dict(build_ext=CMakeBuild),
    zip_safe=False,
)