"""Threaded: send and receive concurrently on the same channel.

Demonstrates using threading to send messages while listening for
incoming messages on a background thread.

Usage:
    export SKYTALE_API_KEY="sk_live_..."
    python threaded.py
"""

import os
import threading
import time
from skytale_sdk import SkytaleClient

RELAY = os.environ.get("SKYTALE_RELAY", "https://relay.skytale.sh:5000")
API_URL = os.environ.get("SKYTALE_API_URL", "https://api.skytale.sh")
API_KEY = os.environ.get("SKYTALE_API_KEY")

kwargs = {}
if API_KEY:
    kwargs["api_key"] = API_KEY
    kwargs["api_url"] = API_URL

# Create two agents and a shared channel
alice = SkytaleClient(RELAY, "/tmp/alice-threaded", b"alice", **kwargs)
bob = SkytaleClient(RELAY, "/tmp/bob-threaded", b"bob", **kwargs)

channel = alice.create_channel("myorg/team/threaded")
print("Alice created channel")

key_package = bob.generate_key_package()
welcome = channel.add_member(key_package)
bob_channel = bob.join_channel("myorg/team/threaded", welcome)
print("Bob joined channel")


# Bob listens in a background thread
def listen(ch, name):
    for msg in ch.messages():
        print(f"  {name} received: {bytes(msg).decode()}")


threading.Thread(target=listen, args=(bob_channel, "Bob"), daemon=True).start()

# Alice sends several messages from the main thread
for i in range(5):
    message = f"Message #{i + 1} from Alice"
    channel.send(message.encode())
    print(f"Alice sent: {message}")
    time.sleep(0.5)

print("\nDone. All messages sent and received concurrently.")
