# Path: pypeman/graph.py
# def wait_for_loop(tmax=5.0):
#     """
#     wait until the loop variable of a pypeman graph
#     has been initialized
# 
#     can be used from any thread that's not the main thread
#     """
#     # TODO: might factor out this function to a helper module
#     loop = None
#     steps = int(tmax / 0.1)
#     for i in range(steps, -1, -1):
#         try:
#             channel = channels.all_channels[0]
#             # print("channel =", channel)
#             loop = channel.loop
#             break
#         except Exception:
#             if i == 0:
#                 raise PypemanError("couldn't obtain graph's loop")
#         time.sleep(0.1)
#     return loop


import os
import sys
import threading
import time
import pypeman.commands
from contextlib import contextmanager
from pypeman.graph import wait_for_loop

tst_lock = threading.Lock()


# migth refactor to a helper directory
@contextmanager
def chdir(path=None):
    """
        enter a certain directory for a given test
    """
    if path is None:
        path = os.path.realpath(os.path.dirname(__file__))
    prev_dir = os.getcwd()
    os.chdir(path)
    yield prev_dir
    os.chdir(prev_dir)


def start_pm_graph():
    try:
        sys.argv[1:] = ["--no-daemon"]
        pypeman.commands.start()
    except SystemExit:
        pass


def tst_thread(errors):
    """
    testing thread for test_one
    """

# Path: pypeman/graph.py
# def wait_for_loop(tmax=5.0):
#     """
#     wait until the loop variable of a pypeman graph
#     has been initialized
# 
#     can be used from any thread that's not the main thread
#     """
#     # TODO: might factor out this function to a helper module
#     loop = None
#     steps = int(tmax / 0.1)
#     for i in range(steps, -1, -1):
#         try:
#             channel = channels.all_channels[0]
#             # print("channel =", channel)
#             loop = channel.loop
#             break
#         except Exception:
#             if i == 0:
#                 raise PypemanError("couldn't obtain graph's loop")
#         time.sleep(0.1)
#     return loop


# Path: examples/some_activity/test_graph.py
import os
import sys
import threading
import time
import pypeman.commands
from contextlib import contextmanager
from pypeman.graph import wait_for_loop


tst_lock = threading.Lock()


# migth refactor to a helper directory
@contextmanager
def chdir(path=None):
    """
        enter a certain directory for a given test
    """
    if path is None:
        path = os.path.realpath(os.path.dirname(__file__))
    prev_dir = os.getcwd()
    os.chdir(path)
    yield prev_dir
    os.chdir(prev_dir)


def start_pm_graph():
    try:
        sys.argv[1:] = ["--no-daemon"]
        pypeman.commands.start()
    except SystemExit:
        pass


def tst_thread(errors):
    """
    testing thread for test_one
    """

    loop = wait_for_loop()