# Path: pyactor/context.py
# def set_context(module_name='thread'):
#     """
#     This function initializes the execution context deciding which
#     type of threads are being used: classic python threads or green
#     threads, provided by Gevent.
# 
#     This should be called first of all in every execution, otherwise,
#     the library would not work.
# 
#     The default module is 'thread'.
# 
#     :param str. module_name: Name of the module you want to use
#         ('thread' or 'green_thread').
#     """
#     global core_type
#     if core_type is None and module_name in available_types:
#         core_type = module_name
#         util.core_type = core_type
#         global actor_module
#         actor_module = import_module('pyactor.' + module_name + '.actor')
#         global intervals
#         intervals = import_module('pyactor.' + module_name + '.intervals')
#         global parallels
#         parallels = import_module('pyactor.' + module_name + '.parallels')
#         global future
#         future = import_module('pyactor.' + module_name + '.future')
#         set_actor(module_name)
#         global rpcactor
#         rpcactor = import_module('pyactor.' + module_name + '.rpcactor')
#         global signal
#         if module_name == 'green_thread':
#             signal = import_module('gevent')
#         else:
#             signal = import_module('signal')
#     else:
#         if core_type is not None:
#             raise Exception("The core type was previously configured.")
#         raise Exception("Bad core type.")
# 
# def create_host(url="local://local:6666/host"):
#     """
#     This is the main function to create a new Host to which you can
#     spawn actors. It will be set by default at local address if no
#     parameter *url* is given. This function should be called once
#     for execution or after calling :meth:`~.shutdown` to the previous
#     host.
# 
#     However, it is possible to create locally more than one host
#     and simulate a remote communication between them if they are of some
#     remote type (`http` or `amqp`), but the first one created will
#     be the main host, which is the one hosting the queries from
#     the main function.
#     Of course, every host must be initialized with a different URL(port).
#     Although that, more than one host should not be required for any real
#     project.
# 
#     :param str. url: URL where to start and bind the host.
#     :return: :class:`~.Proxy` to the new host created.
#     :raises: Exception if there is a host already created with that URL.
#     """
#     if url in util.hosts.keys():
#         raise HostError("Host already created. Only one host can"
#                         " be ran with the same url.")
#     else:
#         if not util.hosts:
#             util.main_host = Host(url)
#             util.hosts[url] = util.main_host
#         else:
#             util.hosts[url] = Host(url)
#         return util.hosts[url].proxy
# 
# def sleep(seconds):
#     """
#     Facade for the sleep function. Do not use time.sleep if you are
#     running green threads.
#     """
#     intervals.sleep(seconds)
# 
# def shutdown(self):
#     # """
#     # For internal calls.
#     # """
#     if self.alive:
#         print(f"Host {self.addr} :#: shutting down...")
#         for interval_event in self.intervals.values():
#             interval_event.set()
# 
#         for actor in self.actors.values():
#             Proxy(actor).stop()
# 
#         # stop the pool (close & join)
#         if self.ppool is not None:
#             if core_type == 'thread':
#                 self.ppool.close()
#             self.ppool.join()
# 
#         # By now, all pthreads should be gone
#         for parallel in self.pthreads.keys():
#             parallel.join()
# 
#         for thread in self.threads.keys():
#             try:
#                 thread.join()
#             except Exception as e:
#                 print(e)
# 
#         self.locks.clear()
#         self.actors.clear()
#         self.threads.clear()
#         self.pthreads.clear()
#         self.running = False
#         self.alive = False
# 
#         del util.hosts[self.url]
#         if util.main_host.url == self.url:
#             util.main_host = (list(util.hosts.values())[0]
#                               if util.hosts.values() else None)
# 
#         print(f"Host {self.addr} :#: Bye!")
# 
# Path: pyactor/exceptions.py
# class PyActorTimeoutError(Exception):
#     """Wait time expired."""
# 
#     def __init__(self, method='Not specified'):
#         self.method = method
# 
#     def __str__(self):
#         return f"Timeout triggered: {self.method!r}"


from pyactor.context import set_context, create_host, sleep, shutdown
from pyactor.exceptions import PyActorTimeoutError
    def __init__(self):
        self.count = 0

    def work(self):
        sl = self.host.spawn('sl', Work)
        for i in range(5):
            print(f"working {i}")
            sl.sleeping(2, timeout=3)
            self.count += 1
        # return True

    def check_work(self):
        return self.count


if __name__ == '__main__':
    # set_context('green_thread')
    set_context()

    host = create_host()
    worker = host.spawn('w1', ParaWork)

    try:
        worker.work()
    except PyActorTimeoutError as e:
        print(e)

    for i in range(10):
        try:
            print(worker.check_work(timeout=None))

# Path: pyactor/context.py
# def set_context(module_name='thread'):
#     """
#     This function initializes the execution context deciding which
#     type of threads are being used: classic python threads or green
#     threads, provided by Gevent.
# 
#     This should be called first of all in every execution, otherwise,
#     the library would not work.
# 
#     The default module is 'thread'.
# 
#     :param str. module_name: Name of the module you want to use
#         ('thread' or 'green_thread').
#     """
#     global core_type
#     if core_type is None and module_name in available_types:
#         core_type = module_name
#         util.core_type = core_type
#         global actor_module
#         actor_module = import_module('pyactor.' + module_name + '.actor')
#         global intervals
#         intervals = import_module('pyactor.' + module_name + '.intervals')
#         global parallels
#         parallels = import_module('pyactor.' + module_name + '.parallels')
#         global future
#         future = import_module('pyactor.' + module_name + '.future')
#         set_actor(module_name)
#         global rpcactor
#         rpcactor = import_module('pyactor.' + module_name + '.rpcactor')
#         global signal
#         if module_name == 'green_thread':
#             signal = import_module('gevent')
#         else:
#             signal = import_module('signal')
#     else:
#         if core_type is not None:
#             raise Exception("The core type was previously configured.")
#         raise Exception("Bad core type.")
# 
# def create_host(url="local://local:6666/host"):
#     """
#     This is the main function to create a new Host to which you can
#     spawn actors. It will be set by default at local address if no
#     parameter *url* is given. This function should be called once
#     for execution or after calling :meth:`~.shutdown` to the previous
#     host.
# 
#     However, it is possible to create locally more than one host
#     and simulate a remote communication between them if they are of some
#     remote type (`http` or `amqp`), but the first one created will
#     be the main host, which is the one hosting the queries from
#     the main function.
#     Of course, every host must be initialized with a different URL(port).
#     Although that, more than one host should not be required for any real
#     project.
# 
#     :param str. url: URL where to start and bind the host.
#     :return: :class:`~.Proxy` to the new host created.
#     :raises: Exception if there is a host already created with that URL.
#     """
#     if url in util.hosts.keys():
#         raise HostError("Host already created. Only one host can"
#                         " be ran with the same url.")
#     else:
#         if not util.hosts:
#             util.main_host = Host(url)
#             util.hosts[url] = util.main_host
#         else:
#             util.hosts[url] = Host(url)
#         return util.hosts[url].proxy
# 
# def sleep(seconds):
#     """
#     Facade for the sleep function. Do not use time.sleep if you are
#     running green threads.
#     """
#     intervals.sleep(seconds)
# 
# def shutdown(self):
#     # """
#     # For internal calls.
#     # """
#     if self.alive:
#         print(f"Host {self.addr} :#: shutting down...")
#         for interval_event in self.intervals.values():
#             interval_event.set()
# 
#         for actor in self.actors.values():
#             Proxy(actor).stop()
# 
#         # stop the pool (close & join)
#         if self.ppool is not None:
#             if core_type == 'thread':
#                 self.ppool.close()
#             self.ppool.join()
# 
#         # By now, all pthreads should be gone
#         for parallel in self.pthreads.keys():
#             parallel.join()
# 
#         for thread in self.threads.keys():
#             try:
#                 thread.join()
#             except Exception as e:
#                 print(e)
# 
#         self.locks.clear()
#         self.actors.clear()
#         self.threads.clear()
#         self.pthreads.clear()
#         self.running = False
#         self.alive = False
# 
#         del util.hosts[self.url]
#         if util.main_host.url == self.url:
#             util.main_host = (list(util.hosts.values())[0]
#                               if util.hosts.values() else None)
# 
#         print(f"Host {self.addr} :#: Bye!")
# 
# Path: pyactor/exceptions.py
# class PyActorTimeoutError(Exception):
#     """Wait time expired."""
# 
#     def __init__(self, method='Not specified'):
#         self.method = method
# 
#     def __str__(self):
#         return f"Timeout triggered: {self.method!r}"


# Path: examples/parall.py
from pyactor.context import set_context, create_host, sleep, shutdown
from pyactor.exceptions import PyActorTimeoutError

    def __init__(self):
        self.count = 0

    def work(self):
        sl = self.host.spawn('sl', Work)
        for i in range(5):
            print(f"working {i}")
            sl.sleeping(2, timeout=3)
            self.count += 1
        # return True

    def check_work(self):
        return self.count


if __name__ == '__main__':
    # set_context('green_thread')
    set_context()

    host = create_host()
    worker = host.spawn('w1', ParaWork)

    try:
        worker.work()
    except PyActorTimeoutError as e:
        print(e)

    for i in range(10):
        try:
            print(worker.check_work(timeout=None))

            sleep(1)