"""
CORSIKA Reader
===============

This package is a utility to read files generated by CORSIKA.  CORSIKA
(COsmic Ray SImulations for KAscade) is a program for detailed
simulation of extensive air showers initiated by high energy cosmic
ray particles. Protons, light nuclei up to iron, photons, and many
other particles may be treated as primaries.

"""

import os
import sys
import glob
import shutil

import platform
import subprocess

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


# this is a hack... the original module defines example_data_dir but this is not known a priory
# this tiny module wraps it and defines the variable
_module_file = """from .corsika import *
import os
example_data_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                example_data_dir)
del os
"""

class CustomExtension(Extension):
    def __init__(self, name, sourcedir=''):
        Extension.__init__(self, name, sources=[])
        self.sourcedir = os.path.abspath(sourcedir)

class CustomBuild(build_ext):
    def run(self):
        if platform.system() == "Windows":
            raise RuntimeError("this thing has never ever been built on Windows...")

        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)))
        try:
            import numpy
        except:
            raise Exception("numpy is not present. Build will fail")

        build_cmd = ['make','install']

        config_cmd = ['cmake',
                      ext.sourcedir,
                      #'-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir,
                      '-DCMAKE_INSTALL_PREFIX={}'.format(extdir),
                      '-DCORSIKA_EXAMPLE_DATA_DIR='+os.path.join('data')
        ]
        if self.debug:
            config_cmd.append('-DCMAKE_BUILD_TYPE=Debug')
        print(' '.join(config_cmd))
        if not os.path.exists(self.build_temp):
            os.makedirs(self.build_temp)

        print('extdir: {}'.format(extdir))
        print('build_temp: {}'.format(self.build_temp))

        subprocess.check_call(config_cmd, cwd=self.build_temp, env=os.environ)
        subprocess.check_call(build_cmd, cwd=self.build_temp, env=os.environ)

        shutil.move(os.path.join(extdir,'share','corsika'),os.path.join(extdir, 'corsika'))
        for l in glob.glob(os.path.join(extdir,'lib', '*')):
            b = os.path.basename(l)
            shutil.move(l, os.path.join(extdir, 'corsika', b))
        shutil.rmtree(os.path.join(extdir,'share'))
        shutil.rmtree(os.path.join(extdir,'lib'))
        shutil.rmtree(os.path.join(extdir,'include'))
        with open(os.path.join(extdir, 'corsika', '__init__.py'), 'w') as f:
            f.write(_module_file)

setup(
    name='corsika-reader',
    version='0.2',
    description='A utility to read files generated by CORSIKA',

    # parameters from now on are optional
    long_description=__doc__,

    url='https://github.com/IceCubeOpenSource/corsika_reader',
    author='Javier G. Gonzalez',
    author_email='javierggt@yahoo.com',

    #install_requires=[''],

    ext_modules=[CustomExtension('corsika_reader')],
    cmdclass={'build_ext':CustomBuild,},
    zip_safe=False,
    packages=find_packages(),

    # Classifiers help users find your project by categorizing it.
    #
    # For a list of valid classifiers, see
    # https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        # How mature is this project? Common values are
        #   3 - Alpha
        #   4 - Beta
        #   5 - Production/Stable
        'Development Status :: 4 - Beta',

        # Indicate who your project is intended for
        'Intended Audience :: Education',
        'Intended Audience :: Science/Research',
        'Topic :: Scientific/Engineering :: Physics',

        # Pick your license as you wish
        'License :: OSI Approved :: MIT License',

        # Specify the Python versions you support here. In particular, ensure
        # that you indicate whether you support Python 2, Python 3 or both.
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3'
    ],

    # Note that this is a string of words separated by whitespace, not a list.
    # keywords='',

    # List additional URLs that are relevant to your project as a dict.
    #
    # This field corresponds to the "Project-URL" metadata fields:
    # https://packaging.python.org/specifications/core-metadata/#project-url-multiple-use
    #
    # Examples listed include a pattern for specifying where the package tracks
    # issues, where the source is hosted, where to say thanks to the package
    # maintainers, and where to support the project financially. The key is
    # what's used to render the link text on PyPI.
    # project_urls={
    #    'Bug Reports': 'https://github.com/pypa/sampleproject/issues',
    #    'Funding': 'https://donate.pypi.org',
    #    'Say Thanks!': 'http://saythanks.io/to/example',
    #    'Source': 'https://github.com/pypa/sampleproject/',
    #},
)
