"""
Initialization script for Nano when bundled by cx_Freeze.
This is made from the base cx_Freeze init script "Console.py".
"""
import os
import sys

sys.frozen = True  # cx_Freeze solution for the program to detect frozen runtime
DIR_NAME = os.path.dirname(sys.executable)

if sys.platform.startswith("win"):
    # NOTE: If Long-path support is not enabled, the Windows shell cannot even chdir to the executable to launch it.
    # This means executables under long path without the enabled support cannot be started. If we prefixed the
    # DIR_NAME here with "\\?\" for example, it would not solve anything.

    # Since the root directory is the one that contains the executables, adding it as a DLL lookup directory is
    # not necessary. We have it here so we don't forget about it if the location of the dependant DLLs change.
    os.add_dll_directory(DIR_NAME)
elif sys.platform.startswith("darwin"):
    pass
else:
    def _setup_gtk3_resources():
        # check and setup extra gtk3 binding modules for wxWidgets
        m_cache = os.path.join(DIR_NAME, "lib", "gdk-pixbuf-2.0", "loaders.cache")
        m_dir = m_cache.rpartition(".")[0]
        if os.path.isfile(m_cache) and os.path.isdir(m_dir):
            os.environ["GDK_PIXBUF_MODULEDIR"] = m_dir
            os.environ["GDK_PIXBUF_MODULE_FILE"] = m_cache
        m_schemas = os.path.join(DIR_NAME, "lib", "glib-schemas")
        if os.path.isdir(m_schemas):
            os.environ["GSETTINGS_SCHEMA_DIR"] = m_schemas

    _setup_gtk3_resources()

# This is used by the core mostly.
os.environ["CBNANO_ROOT"] = DIR_NAME


def run(name):
    code = __loader__.get_code(name)
    module_main = __import__("__main__")
    module_main.__dict__["__file__"] = code.co_filename
    exec(code, module_main.__dict__)
