import os
import pathlib
import platform
import shutil
import sys
from distutils.version import StrictVersion
import warnings


# On Windows prepend the path to our dlls to the PATH environment variable.
# Otherwise our dlls won't be found when our Python extensions are loaded
# by Python.
if sys.platform == "win32":
    pcraster_app_path = shutil.which("pcrcalc.exe")
    if pcraster_app_path:
        pcraster_bin_pathname = pathlib.Path(pcraster_app_path).parent
        os.add_dll_directory(pcraster_bin_pathname)


# Check if we can import our compiled module
try:
    from ._pcraster import *
except ImportError as error:
    # Test matching Python versions
    major, minor, patchlevel = platform.python_version_tuple()
    major = int(major)

    # if major != 3:
    if StrictVersion("{}.{}".format(major, minor)) != StrictVersion("3.9"):
        msg = "The 'pcraster' module was built for Python 3.9, the version used is {}.{}".format(
            major, minor)
        raise ImportError(msg)

    # Test matching bitness
    nr_bits = 64 if sys.maxsize > 2**32 else 32

    if nr_bits != 64:
        msg = "The 'pcraster' module was built for 64-bit, the Python version used is {}-bit".format(
            nr_bits)
        raise ImportError(msg)

    # Too old Python 2 versions might not work
    if major == 2:
        if StrictVersion("{}.{}".format(major, minor)) < StrictVersion("2.7"):
            msg = "The 'pcraster' module was built for Python 3.9, the version used is {}.{}".format(
                major, minor)
            warnings.warn(msg, RuntimeWarning)

    msg = ""

    # VS2017 and runtime components related issues
    if sys.platform == "win32":
        if StrictVersion("{}.{}".format(major, minor)) != StrictVersion("3.9"):
            msg += "The 'pcraster' module was built for Python 3.9, the version used is {}.{}".format(
                major, minor)
            raise ImportError(msg)

        msg += "The 'Microsoft Visual C++ Redistributable for Visual Studio 2017' is required to run PCRaster, available at:\n"
        msg += "https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads\n"

    # Something else went wrong...
    msg += "{}\n".format(error)
    msg += "In case you cannot solve the issue please consult the PCRaster mailing list at:\nhttps://lists.geo.uu.nl/mailman/listinfo/pcraster-info\n"
    raise ImportError(msg)
except Exception as error:
    raise error


# If importing the compiled module succeeds everything else should be fine as well
from .operations import *
from . import operators
from .aguila import *
from .numpy_operations import *
from .__about__ import (
    __version__, __author__, __uri__, __license__, __copyright__
)

try:
    from ._pcraster_modflow import *
except ImportError:
    pass  # Modflow module was not installed

try:
    _var = "PCRASTER_NR_WORKER_THREADS"
    _workers = int(os.environ[_var])
    from .multicore import *
    set_nr_worker_threads(_workers)
except ValueError as err:
    msg = "Could not obtain the number of worker threads. The environment variable {} is set to '{}'; use an integer value instead.".format(
        _var, os.environ[_var])
    raise RuntimeError(msg)
except KeyError:
    pass  # No multicore module use intended
except ImportError:
    pass  # Multicore module was not installed


try:
    import matplotlib
    from .matplotlib import plot

except ImportError as e:
    pass  # Matplotlib module was not installed
