import os
import sys
import contextlib

from ..vendor.Qt import QtWidgets, QtCore, QtGui

self = sys.modules[__name__]
self._jobs = dict()
self._path = os.path.dirname(__file__)


def resource(*path):
    path = os.path.join(self._path, "_res", *path)
    return path.replace("\\", "/")


def install_fonts():
    database = QtGui.QFontDatabase()

    for font in ("fontawesome/FontAwesome.otf",
                 "opensans/OpenSans-Regular.ttf"):
        path = resource("font", font)

        if database.addApplicationFont(path) < 0:
            sys.stderr.write("Could not install %s\n" % path)
        else:
            sys.stdout.write("Installed %s\n" % font)


@contextlib.contextmanager
def application():
    app = QtWidgets.QApplication.instance()

    if not app:
        print("Starting new QApplication..")
        app = QtWidgets.QApplication(sys.argv)
        install_fonts()
        yield app
        app.exec_()
    else:
        print("Using existing QApplication..")
        install_fonts()
        yield app


def defer(delay, func):
    """Append artificial delay to `func`

    This aids in keeping the GUI responsive, but complicates logic
    when producing tests. To combat this, the environment variable ensures
    that every operation is synchonous.

    Arguments:
        delay (float): Delay multiplier; default 1, 0 means no delay
        func (callable): Any callable

    """

    delay *= float(os.getenv("PYBLISH_DELAY", 1))
    if delay > 0:
        return QtCore.QTimer.singleShot(delay, func)
    else:
        return func()


def schedule(func, time, channel="default"):
    """Run `func` at a later `time` in a dedicated `channel`

    Given an arbitrary function, call this function after a given
    timeout. It will ensure that only one "job" is running within
    the given channel at any one time and cancel any currently
    running job if a new job is submitted before the timeout.

    """

    try:
        self._jobs[channel].stop()
    except (AttributeError, KeyError):
        pass

    timer = QtCore.QTimer()
    timer.setSingleShot(True)
    timer.timeout.connect(func)
    timer.start(time)

    self._jobs[channel] = timer


@contextlib.contextmanager
def dummy():
    """Dummy context manager

    Usage:
        >> with some_context() if False else dummy():
        ..   pass

    """

    yield

import os
import sys
import contextlib

from ..vendor.Qt import QtWidgets, QtCore, QtGui

self = sys.modules[__name__]
self._jobs = dict()
self._path = os.path.dirname(__file__)


def resource(*path):
    path = os.path.join(self._path, "_res", *path)
    return path.replace("\\", "/")


def install_fonts():
    database = QtGui.QFontDatabase()

    for font in ("opensans/OpenSans-Regular.ttf",):
        path = resource("font", font)

        if database.addApplicationFont(path) < 0:
            sys.stderr.write("Could not install %s\n" % path)
        else:
            sys.stdout.write("Installed %s\n" % font)


@contextlib.contextmanager
def application():
    app = QtWidgets.QApplication.instance()

    if not app:
        print("Starting new QApplication..")
        app = QtWidgets.QApplication(sys.argv)
        install_fonts()
        yield app
        app.exec_()
    else:
        print("Using existing QApplication..")
        install_fonts()
        yield app


def defer(delay, func):
    """Append artificial delay to `func`

    This aids in keeping the GUI responsive, but complicates logic
    when producing tests. To combat this, the environment variable ensures
    that every operation is synchonous.

    Arguments:
        delay (float): Delay multiplier; default 1, 0 means no delay
        func (callable): Any callable

    """

    delay *= float(os.getenv("PYBLISH_DELAY", 1))
    if delay > 0:
        return QtCore.QTimer.singleShot(delay, func)
    else:
        return func()


def schedule(func, time, channel="default"):
    """Run `func` at a later `time` in a dedicated `channel`

    Given an arbitrary function, call this function after a given
    timeout. It will ensure that only one "job" is running within
    the given channel at any one time and cancel any currently
    running job if a new job is submitted before the timeout.

    """

    try:
        self._jobs[channel].stop()
    except (AttributeError, KeyError):
        pass

    timer = QtCore.QTimer()
    timer.setSingleShot(True)
    timer.timeout.connect(func)
    timer.start(time)

    self._jobs[channel] = timer


@contextlib.contextmanager
def dummy():
    """Dummy context manager

    Usage:
        >> with some_context() if False else dummy():
        ..   pass

    """

    yield

Discard notion of Awesome Font outside of qtawesome