# Path: src/petmail/scripts/webwait.py
# def follow_events(basedir, topic, catchup=False, err=sys.stderr):
#     if _debug_no_http:
#         raise RuntimeError("unit-test support not implemented yet")
#     baseurl, token = get_url_and_token(basedir, err)
#     if not baseurl:
#         return False, {"err": "Error, node is not yet running"}
#     # first, create the event channel
#     resp = do_http("POST", baseurl + "api/eventchannel-create",
#                    json.dumps({"token": token}))
#     if resp.status != 200:
#         raise RuntimeError("unable to create event channel: %s %s"
#                            % (resp.status, resp.reason))
#     r = json.loads(resp.read().decode("utf-8"))
#     esid = r["esid"]
#     # we'll listen on this one
#     event_resp = do_http("GET", baseurl + "api/events/%s" % esid,
#                          event_stream=True)
#     # and then subscribe to hear about events. I'm not 100% sure this won't
#     # race (the web frontend specifically waits until a "ready" event is
#     # delivered, to make sure the browser has established the EventSource
#     # channel, before subscribing to anything. We're ok as long as do_http()
#     # doesn't return until after it's seen the HTTP headers.
#     resp = do_http("POST", baseurl + "api/eventchannel-subscribe",
#                    json.dumps({"token": token,
#                                "args": {"esid": esid,
#                                         "topic": topic,
#                                         "catchup": catchup}}))
#     if resp.status != 200:
#         raise RuntimeError("unable to subscribe to event channel: %s %s"
#                            % (resp.status, resp.reason))
# 
#     return event_resp
# 
# def get_field(r):
#     first_line = get_line(r)
#     fieldname, data = first_line.split(": ", 1)
#     lines = [data]
#     while True:
#         line = get_line(r)
#         if not line:
#             return fieldname, "\n".join(lines)
#         lines.append(line)


import json
from .webwait import follow_events, get_field

def render_message(msg):
    lines = []
    lines.append('== %d: from %s (cid=%d #%d):' % (
        msg["id"], msg["petname"], msg["cid"], msg["seqnum"]))
    payload = json.loads(msg["payload_json"])
    if "basic" in payload:
        lines.append(" basic: " + payload["basic"])
    else:
        lines.append(str(msg["payload_json"]))
    return "\n".join(lines)+"\n"


def follow_messages(so, stdout, stderr):
    try:

# Path: src/petmail/scripts/webwait.py
# def follow_events(basedir, topic, catchup=False, err=sys.stderr):
#     if _debug_no_http:
#         raise RuntimeError("unit-test support not implemented yet")
#     baseurl, token = get_url_and_token(basedir, err)
#     if not baseurl:
#         return False, {"err": "Error, node is not yet running"}
#     # first, create the event channel
#     resp = do_http("POST", baseurl + "api/eventchannel-create",
#                    json.dumps({"token": token}))
#     if resp.status != 200:
#         raise RuntimeError("unable to create event channel: %s %s"
#                            % (resp.status, resp.reason))
#     r = json.loads(resp.read().decode("utf-8"))
#     esid = r["esid"]
#     # we'll listen on this one
#     event_resp = do_http("GET", baseurl + "api/events/%s" % esid,
#                          event_stream=True)
#     # and then subscribe to hear about events. I'm not 100% sure this won't
#     # race (the web frontend specifically waits until a "ready" event is
#     # delivered, to make sure the browser has established the EventSource
#     # channel, before subscribing to anything. We're ok as long as do_http()
#     # doesn't return until after it's seen the HTTP headers.
#     resp = do_http("POST", baseurl + "api/eventchannel-subscribe",
#                    json.dumps({"token": token,
#                                "args": {"esid": esid,
#                                         "topic": topic,
#                                         "catchup": catchup}}))
#     if resp.status != 200:
#         raise RuntimeError("unable to subscribe to event channel: %s %s"
#                            % (resp.status, resp.reason))
# 
#     return event_resp
# 
# def get_field(r):
#     first_line = get_line(r)
#     fieldname, data = first_line.split(": ", 1)
#     lines = [data]
#     while True:
#         line = get_line(r)
#         if not line:
#             return fieldname, "\n".join(lines)
#         lines.append(line)


# Path: src/petmail/scripts/messages.py
import json
from .webwait import follow_events, get_field


def render_message(msg):
    lines = []
    lines.append('== %d: from %s (cid=%d #%d):' % (
        msg["id"], msg["petname"], msg["cid"], msg["seqnum"]))
    payload = json.loads(msg["payload_json"])
    if "basic" in payload:
        lines.append(" basic: " + payload["basic"])
    else:
        lines.append(str(msg["payload_json"]))
    return "\n".join(lines)+"\n"


def follow_messages(so, stdout, stderr):
    try:

        resp = follow_events(so["basedir"], "messages", catchup=True)