#!/usr/bin/env python

import os
import re
import shutil
import subprocess
import sys
from setuptools import setup
from distutils.command.clean import clean as _clean
from distutils.command.build_py import build_py_2to3 as _build_py

# @brief Creates Protobuf python files to encode and decode messages
# @param[in] source The protobuf source file
def generateProtobuf(source):
    output = source.replace('.proto', '_pb2.py').replace('src/protobuf/', 'aman/com/')

    if (not os.path.exists(output) or (os.path.exists(source) and os.path.getmtime(source) > os.path.getmtime(output))):
        print('Generating %s...' % output)

        if not os.path.exists(source):
            sys.stderr.write('Cannot find %s' % source)
            sys.exit(-1)

        if not os.path.exists('external/bin/protoc.exe'):
            sys.stderr.write('Cannot find proto-compiler')
            sys.exit(-1)

        command = [ 'external/bin/protoc.exe', '-Isrc/protobuf/', '-I.', '--python_out=aman/com/', source]
        if 0 != subprocess.call(command):
            sys.exit(-1)

        # check if we need to replace some import commands
        replaced = False
        content = open(output, 'r').read()
        for entry in re.findall('import.[A-Z].*.as.*', content):
            content = content.replace(entry, 'from . ' + entry)
            replaced = True

        # update the content
        if replaced:
            with open(output, 'w') as file:
                file.write(content)

# @brief Cleans up all auto-generated files and folders
# @param[in] _clean Instance of setuptools to clean up the system
class clean(_clean):
    def run(self):
        for (dirpath, dirnames, filenames) in os.walk('.'):
            for filename in filenames:
                filepath = os.path.join(dirpath, filename)
                if filepath.endswith('_pb2.py') or filepath.endswith('.pyc'):
                    os.remove(filepath)
            for dirname in dirnames:
                if 'Arrival_MANager.egg-info' == dirname or 'build' == dirname or 'dist' == dirname or '__pycache__' == dirname:
                    shutil.rmtree(os.path.join(dirpath, dirname))
        _clean.run(self)

# @brief Generates the python files and folders to set up the development/runtime environment
# @param[in] _build_py Instance of setuptools to build the system
class build_py(_build_py):
    def run(self):
        generateProtobuf('src/protobuf/Aircraft.proto')
        generateProtobuf('src/protobuf/AircraftReport.proto')
        generateProtobuf('src/protobuf/AircraftSchedule.proto')
        generateProtobuf('src/protobuf/BaseTypes.proto')
        _build_py.run(self)

with open('README.md', 'r') as f:
    longDescription = f.read()

setup(
    name = 'Arrival MANager',
    version = '0.1.0',
    packages = [
        'aman',
        'aman.com',
        'aman.config',
        'aman.tools',
        'aman.types'
    ],
    namespace_packages = [ 'aman' ],
    description = 'AMAN optimization backend',
    long_description = longDescription,
    author = 'Sven Czarnian',
    author_email = 'devel@svcz.de',
    license = 'GPLv3',
    cmdclass = { 'clean': clean, 'build_py': build_py },
    install_requires=[
        'argparse',
        'configparser',
        'numpy',
        'protobuf',
        'pyzmq',
        'scikit-learn',
        'scipy',
        'setuptools'
    ]
)