"""
Placeholders:
    LIB_RELDIR
    SITE_PACKAGES
    EXTEND_SYS_PATHS
    TARGET_RELDIR
    TARGET_PKG
    TARGET_NAME
    TARGET_FUNC
    TARGET_ARGS
    TARGET_KWARGS

References:
    pyportable_installer/no3_build_pyproject.py > func:_create_launcher
"""
import os
import sys

# add current dir to sys.path (this is necessary for embed python)
sys.path.append(os.path.abspath('.'))

# add lib to environment
sys.path.append(os.path.abspath('{LIB_RELDIR}'))

site_packages = '{SITE_PACKAGES}'
if site_packages:  # see `pyportable_installer/main.py:_copy_venv`
    sys.path.append(os.path.abspath(site_packages))

extra_paths = {EXTEND_SYS_PATHS}
if extra_paths:
    sys.path.extend(map(os.path.abspath, extra_paths))

# ------------------------------------------------------------------------------


def launch(main_func, *args, **kwargs):
    """
    Usage:
        # my_main.py
        from lk_utils.easy_launcher import launch

        def main(a, b):
            print(a + b)

        launch(main, a=1, b=2)
    """

    # noinspection PyUnusedLocal
    def show_err_on_console(err):
        print('Runtime Error:', err)
        input('Press any key to leave...')

    # noinspection PyUnusedLocal
    def show_err_on_msgbox(err):
        # notes: not recommend to use
        # https://stackoverflow.com/questions/17280637/tkinter-messagebox
        # -without-window
        from tkinter import Tk, messagebox
        root = Tk()
        root.withdraw()
        messagebox.showerror(title='Runtime Error', message=err)

    # noinspection PyUnusedLocal
    def alert(title, msg):
        # https://www.cnblogs.com/freeweb/p/5048833.html
        return os.popen(
            'echo msgbox "{{msg}}", 64, "{{title}}" > '
            'alert.vbs && start '
            'alert.vbs && ping -n 2 127.1 > '
            'nul && del alert.vbs'.format(
                title=title, msg=msg
            )
        ).read()

    try:
        main_func(*args, **kwargs)
    except Exception as e:
        print(e)
        # To obtain more message about this error.
        # https://stackoverflow.com/questions/1278705/when-i-catch-an
        #   -exception-how-do-i-get-the-type-file-and-line-number
        import traceback
        msg = traceback.format_exc()
        alert('Runtime Error', msg)
        # # show_err_on_msgbox(msg)
        # # show_err_on_console(msg)
    finally:
        input('Press enter to leave...')
        sys.exit()


if __name__ == '__main__':
    # 确保所有引用文件时的相对路径都是相对于 TARGET_PKG 的
    os.chdir('{TARGET_RELDIR}')

    if '{TARGET_FUNC}' == '':
        raise ImportError('No target found')
    elif '{TARGET_FUNC}' == '*':
        from {TARGET_PKG}.{TARGET_NAME} import *
    else:
        from {TARGET_PKG}.{TARGET_NAME} import {TARGET_FUNC} as main
        launch(main, *{TARGET_ARGS}, **{TARGET_KWARGS})
