#! /usr/bin/env python
# License: 3-clause BSD

import sys
import os
import platform
import shutil
import tempfile
from distutils.command.build_py import build_py
from distutils.command.sdist import sdist
from distutils.command.clean import clean as Clean
from distutils.errors import CompileError, LinkError
from pkg_resources import parse_version
import traceback

# Get version and release info, which is all stored in pulse2percept/info.py
ver_file = os.path.join('pulse2percept', 'version.py')
with open(ver_file) as f:
    exec(f.read())

VERSION = __version__

NUMPY_MIN_VERSION = '1.9.0'
SCIPY_MIN_VERSION = '1.0'
CYTHON_MIN_VERSION = '0.28'
JOBLIB_MIN_VERSION = '0.11'

DISTNAME = 'pulse2percept'
DESCRIPTION = 'A Python-based simulation framework for bionic vision'
with open('README.rst') as f:
    LONG_DESCRIPTION = f.read()
MAINTAINER = 'Michael Beyeler, Ariel Rokem'
MAINTAINER_EMAIL = 'mbeyeler@ucsb.edu, arokem@gmail.com'
URL = 'https://github.com/pulse2percept/pulse2percept'
DOWNLOAD_URL = 'https://pypi.org/project/pulse2percept/#files'
LICENSE = 'new BDS'
PROJECT_URLS = {
    'Bug Tracker': 'https://github.com/pulse2percept/pulse2percept/issues',
    'Documentation': 'https://pulse2percept.github.io/pulse2percept',
    'Source Code': 'https://github.com/pulse2percept/pulse2percept'
}
CLASSIFIERS = ['Intended Audience :: Science/Research',
               'Intended Audience :: Developers',
               'License :: OSI Approved',
               'Programming Language :: C',
               'Programming Language :: Python',
               'Topic :: Software Development',
               'Topic :: Scientific/Engineering',
               'Operating System :: Microsoft :: Windows',
               'Operating System :: POSIX',
               'Operating System :: Unix',
               'Operating System :: MacOS',
               'Programming Language :: Python :: 3',
               'Programming Language :: Python :: 3.5',
               'Programming Language :: Python :: 3.6',
               'Programming Language :: Python :: 3.7',
               'Programming Language :: Python :: 3.8',
               ('Programming Language :: Python :: '
                'Implementation :: CPython'),
               ('Programming Language :: Python :: '
                'Implementation :: PyPy')
               ]

# Optional setuptools features
# We need to import setuptools early, if we want setuptools features,
# as it monkey-patches the 'setup' function
# For some commands, use setuptools
SETUPTOOLS_COMMANDS = {
    'develop', 'release', 'bdist_egg', 'bdist_rpm',
    'bdist_wininst', 'install_egg_info', 'build_sphinx',
    'egg_info', 'easy_install', 'upload', 'bdist_wheel',
    '--single-version-externally-managed',
}
if SETUPTOOLS_COMMANDS.intersection(sys.argv):
    import setuptools

    extra_setuptools_args = dict(
        zip_safe=False,  # the package can run out of an .egg file
        include_package_data=True,
        extras_require={
            'alldeps': (
                f'numpy >= {NUMPY_MIN_VERSION}',
                f'scipy >= {SCIPY_MIN_VERSION}'
            ),
        },
    )
else:
    extra_setuptools_args = dict()


class CleanCommand(Clean):
    """Custom clean command to remove build artifacts"""
    description = "Remove build artifacts from the source tree"

    def run(self):
        Clean.run(self)
        # Remove c files if we are not within a sdist package
        cwd = os.path.abspath(os.path.dirname(__file__))
        remove_c_files = not os.path.exists(os.path.join(cwd, 'PKG-INFO'))
        if remove_c_files:
            print('Will remove generated .c files')
        if os.path.exists('build'):
            shutil.rmtree('build')
        for dirpath, dirnames, filenames in os.walk('pulse2percept'):
            for filename in filenames:
                if any(filename.endswith(suffix) for suffix in
                       (".so", ".pyd", ".dll", ".pyc")):
                    os.unlink(os.path.join(dirpath, filename))
                    continue
                extension = os.path.splitext(filename)[1]
                if remove_c_files and extension in ['.c', '.cpp']:
                    pyx_file = str.replace(filename, extension, '.pyx')
                    if os.path.exists(os.path.join(dirpath, pyx_file)):
                        os.unlink(os.path.join(dirpath, filename))
            for dirname in dirnames:
                if dirname == '__pycache__':
                    shutil.rmtree(os.path.join(dirpath, dirname))


def openmp_build_ext():
    """Add support for OpenMP"""
    from numpy.distutils.command.build_ext import build_ext

    code = """#include <omp.h>
    int main(int argc, char** argv) { return(0); }"""

    class ConditionalOpenMP(build_ext):

        def can_compile_link(self, compile_flags, link_flags):

            cc = self.compiler
            fname = 'test.c'
            cwd = os.getcwd()
            tmpdir = tempfile.mkdtemp()

            try:
                os.chdir(tmpdir)
                with open(fname, 'wt') as fobj:
                    fobj.write(code)
                try:
                    objects = cc.compile([fname],
                                         extra_postargs=compile_flags)