#! /usr/bin/env python
"""
Topics are used to listen for messages, which are typically used
to trigger an action or change in some value.
"""
from autobahn.twisted.component import Component, run
from autobahn.twisted.wamp import ApplicationSession
from twisted.internet.defer import inlineCallbacks


class PublishComponent(ApplicationSession):
    def __init__(self, config):
        super(PublishComponent, self).__init__(config)
        self.debug = config.extra.get("debug", False)
        self.topic = config.extra["topic"]
        self.value = float(config.extra["val"])

    @inlineCallbacks
    def onJoin(self, details):
        if self.debug:
            print("attached to WAMP router")
        try:
            if self.debug:
                print("publishing to {}".format(self.topic))
            result = yield self.publish(self.topic, self.value)
        except Exception as e:
            print(e.error_message())
        else:
            if self.debug:
                print("message published with result:")
            print("Result: ", result)
        self.leave()

    def onDisconnect(self):
        if self.debug:
            print("detached from WAMP router")


if __name__ == "__main__":
    import argparse
    import os

    parser = argparse.ArgumentParser()
    parser.add_argument("topic", help="The topic to publish to")
    parser.add_argument("value", help="The value to publish")
    parser.add_argument("--debug", action="store_true", help="Enable debug output")

    args = parser.parse_args()
    topic = args.topic
    value = args.value
    debug = args.debug

    URL = os.getenv("WAMP_SERVER", "192.168.1.2")

    transport_cfg = dict(
        type="websocket",
        url="ws://{}:8080/ws".format(URL),
        max_retries=-1,
        max_retry_delay=30,
    )
    comp = Component(
        transports=transport_cfg,
        realm="realm1",
        session_factory=PublishComponent,
        extra={"debug": debug, "topic": topic, "val": value},
    )
    run([comp], log_level=None)
