import subprocess
import sys
import os
import re
import contextlib

# check if pip is installed. If not, raise an ImportError
PIP_INSTALLED = True

try:
    import pip
except ImportError:
    PIP_INSTALLED = False

if not PIP_INSTALLED:
    raise ImportError('pip is not installed.')

def install_and_import(package):
    import importlib
    try:
        importlib.import_module(package)
    except ImportError:
        pip.main(['install', package])
    finally:
        globals()[package] = importlib.import_module(package)

# check if setuptools is installed. If not, install setuptools
# automatically using pip.
install_and_import('setuptools')

from setuptools.command.build_ext import build_ext as _build_ext
from distutils import ccompiler, msvccompiler
from distutils.sysconfig import get_python_inc


## fix compiler and build options
COMPILE_OPTIONS = {
        'msvc': ['/0x', '/EHsc'],
        'mingw32': ['-O3', '-ffast-math', '-march=native'],
        'other': ['-O3', '-ffast-math', '-march=native']
}

LINK_OPTIONS = {
        'msvc': [],
        'mingw32': [],
        'other':[]
}

class build_ext_options:
    def build_options(self):
        for e in self.extensions:
            e.extra_compile_args += COMPILE_OPTIONS.get(
                self.compiler.compiler_type, COMPILE_OPTIONS['other'])
        for e in self.extensions:
            e.extra_link_args += LINK_OPTIONS.get(
                    self.compiler.compiler_type, LINK_OPTIONS['other'])

class build_ext(_build_ext, build_ext_options):
    def build_extensions(self):
        build_ext_options.build_options(self)
        _build_ext.build_extensions(self)


def generate_cython():
    cwd = os.path.abspath(os.path.dirname(__file__))
    print("Cythonizing sources")
    p = subprocess.call([sys.executable, os.path.join(cwd,
                             'build_tools',
                             'cythonize.py'),
            'py_stringsimjoin'],
        cwd=cwd)
    if p != 0:
        raise RuntimeError("Running cythonize failed!")

MODULES = {
        "py_stringsimjoin.index.inverted_index_cy": {'sources':["py_stringsimjoin/index/inverted_index_cy.pyx"],
                                                        'comargs':[]            
                                                        },  
        "py_stringsimjoin.index.position_index_cy": {'sources':["py_stringsimjoin/index/position_index_cy.pyx"],
                                                        'comargs':[]            
                                                        },  
        "py_stringsimjoin.similarity_measure.edit_distance": {'sources':["py_stringsimjoin/similarity_measure/edit_distance.pyx"],
                                                        'comargs':[]
                                                        },

        "py_stringsimjoin.similarity_measure.cosine": {'sources':["py_stringsimjoin/similarity_measure/cosine.pyx"],
                                                        'comargs':[]            
                                                        }, 

        "py_stringsimjoin.similarity_measure.dice": {'sources':["py_stringsimjoin/similarity_measure/dice.pyx"],
                                                        'comargs':[]            
                                                        }, 

        "py_stringsimjoin.similarity_measure.jaccard": {'sources':["py_stringsimjoin/similarity_measure/jaccard.pyx"],
                                                        'comargs':[]            
                                                        }, 

        "py_stringsimjoin.join.edit_distance_join_cy": {'sources':["py_stringsimjoin/join/edit_distance_join_cy.pyx",
                                                                   ],
                                                        'comargs':["-I./py_stringsimjoin/index/"]
                                                        },
        "py_stringsimjoin.join.disk_edit_distance_join_cy": {'sources': ["py_stringsimjoin/join/disk_edit_distance_join_cy.pyx",
                    ],
        'comargs': ["-I./py_stringsimjoin/index/"]
        },

        "py_stringsimjoin.join.overlap_coefficient_join_cy": {'sources':["py_stringsimjoin/join/overlap_coefficient_join_cy.pyx",
                                                                    ],
                                                        'comargs':["-I./py_stringsimjoin/index/"]