#!/usr/bin/env python3

import os
import sys


def except_hook(exception_type, exception_value, traceback):
    sys.__excepthook__(exception_type, exception_value, traceback)


sys.excepthook = except_hook  # pyqt5 (>=5.5) will abort if an exception happens in python code when called from Qt, unless we define this


frozen = hasattr(sys, 'frozen')

# We need to mangle Python's import path in case blink is run directly from
# the bin/ directory.
script_dir = os.path.dirname(os.path.realpath(sys.executable if frozen else __file__))
parent_dir = os.path.dirname(script_dir)
if os.path.basename(script_dir) == 'bin' and os.path.exists(os.path.join(parent_dir, 'blink', '__init__.py')):
    # Insert the parent path just before the existing script's path. We need
    # to do this in order to work with debuggers which insert their own paths
    # at the beginning. The script's path is the last Python itself inserted
    # so we should insert just before that.
    try:
        position = sys.path.index(script_dir)
    except ValueError:
        position = 0
    sys.path.insert(position, parent_dir)

if frozen:
    from StringIO import StringIO

    class DivertedStdout(object):
        def __init__(self):
            self._output = StringIO()
            self._file = None

        @property
        def file(self):
            return self._file

        @file.setter
        def file(self, path):
            if self._file is not None:
                raise RuntimeError("output file was already set to: {0._file!r}".format(self))
            f = open(path, 'a', 0)
            # noinspection PyUnresolvedReferences
            f.write(self._output.getvalue())
            self._output.close()
            self._output = f
            self._file = path

        def __getattr__(self, name):
            return getattr(self._output, name)

    sys.stdout = sys.stderr = DivertedStdout()


# Import log last so the created StreamHandler instances have references
# to the replaced sys.std{out,err}
from application import log
log.level.current = log.level.WARNING


if __name__ == '__main__':
    from blink import Blink
    blink = Blink()
    blink.run()
    os._exit(0)