#!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst

import os
import sys

from setuptools import setup, find_packages, Extension
from configparser import ConfigParser


try:
    import numpy
except ImportError:
    print("numpy is required to build this package.", file=sys.stderr)
    print("HINT: execute \"pip install .\"", file=sys.stderr)
    exit(1)


def get_extensions():
    ROOT = os.path.dirname(__file__)
    SRCDIR = os.path.join(ROOT, 'src')
    cfg = {
        'include_dirs': [],
        'libraries': [],
        'define_macros': []
    }

    cdriz_sources = ['cdrizzleapi.c',
                     'cdrizzleblot.c',
                     'cdrizzlebox.c',
                     'cdrizzlemap.c',
                     'cdrizzleutil.c',
                     os.path.join('tests', 'utest_cdrizzle.c')]

    sources = [os.path.join(SRCDIR, x) for x in cdriz_sources]

    cfg['include_dirs'].append(numpy.get_include())
    cfg['include_dirs'].append(SRCDIR)

    if sys.platform != 'win32':
        cfg['libraries'].append('m')

    if sys.platform == 'win32':
        cfg['define_macros'].append(('WIN32', None))
        cfg['define_macros'].append(('__STDC__', 1))
        cfg['define_macros'].append(('_CRT_SECURE_NO_WARNINGS', None))

    return [Extension(str('drizzle.cdrizzle'), sources, **cfg)]


conf = ConfigParser()
conf.read(['setup.cfg'])
metadata = dict(conf.items('metadata'))

PACKAGENAME = metadata.get('package_name', 'packagename')
DESCRIPTION = metadata.get('description', 'Astropy affiliated package')
AUTHOR = metadata.get('author', '')
AUTHOR_EMAIL = metadata.get('author_email', '')
LICENSE = metadata.get('license', 'unknown')
URL = metadata.get('url', 'https://www.stsci.edu')

# Get the long description from the package's docstring
__import__(PACKAGENAME)
package = sys.modules[PACKAGENAME]
LONG_DESCRIPTION = package.__doc__

# Include all .c files, recursively, including those generated by
# Cython, since we can not do this in MANIFEST.in with a "dynamic"
# directory name.
def to_compile(package):
    c_files = []
    for root, dirs, files in os.walk(package):
        for filename in files:
            if filename.endswith('.c') or filename.endswith('.h'):
                c_files.append(
                    os.path.join(
                        os.path.relpath(root, package), filename))
    return c_files


TESTS_REQUIRE = [
    'pytest',
    'pytest-runner'
]

DOCS_REQUIRE = [
    'sphinx',
    'sphinx_automodapi',
    'matplotlib'
]

setup(name=PACKAGENAME,
    description=DESCRIPTION,
    python_requires='>=3.5',
    setup_requires=[],
    install_requires=['Cython', 'astropy'],
    tests_require=TESTS_REQUIRE,
    extras_require={
        'test': TESTS_REQUIRE,
        'docs': DOCS_REQUIRE
    },
    author=AUTHOR,
    author_email=AUTHOR_EMAIL,
    license=LICENSE,
    url=URL,
    long_description=LONG_DESCRIPTION,
    zip_safe=False,
    packages=find_packages(),
    ext_modules=get_extensions(),
)
