
init -1 python:
    class EventQueue(object):
        def __init__(self):
            self.queue = []
            self.freeze = False

        def get_events(self, raw=False):
            return self.queue if raw else [x for x in self.queue if x.wait < 1]

        def freeze(self):
            self.freeze = True

        def unfreeze(self):
            self.freeze = False

        def delay(self, n):
            for i in self.queue:
                i.wait += n

        def tick(self):
            """Causes time to pass."""
            if self.freeze:
                return

            for i in self.queue:
                i.wait -= 1

        def start(self):
            queue = self.queue
            queue = filter(lambda x: (x.wait <= 0) and (x.daytime == game.daytime), queue)
            queue.sort(key=lambda x: x.priority)

            for ev in queue:
                if not ev.requirements_met():
                    continue

                ev.start()

                if ev.label:
                    break

        def is_in_queue(self, ev):
            if isinstance(ev, str):
                return any(i.id == ev for i in self.queue)
            return ev in self.queue

    class Event(object):
        """
        Queue is universal for all instanced objects.
        """

        def __init__(self, id, wait=0, priority=5, daytime=True, req=None, label=None, func=None):
            self.queued = False
            self.id = id
            self.wait = wait
            self.priority = priority
            self.daytime = daytime
            self.req = req
            self.label = label
            self.func = func
            self.queue = eventqueue.queue

            if not renpy.has_label(self.label):
                raise Exception("Supplied label does not exist.")

        def enqueue(self):
            self.queued = True

            if not self in self.queue:
                self.queue.append(self)

        def requirements_met(self):
            if self.req:
                return eval(self.req)
            return True

        def start(self):
            if self in self.queue:
                self.queue.remove(self)

            if self.func:
                self.func()

            if self.label:
                renpy.jump(self.label)

init offset = -5

default eventqueue = EventQueue()
