#!/usr/bin/python3
# ===================================================================
# test MSTT publish
#
# enter topic or subtopic followed by a value
# ===================================================================
from replace_commas_amd_split import *
import user_interface as ui
import paho.mqtt.client as mqtt
import re
broker        = 'localhost'
instance      = 'tom'
topic_default = 'light'
subtopic_root = '/test/house'
# ---- running Python3?
if not ui.running_python3():
    print()
    print('Must run Python3 - exit program')
    print()
    sys.exit()
# ---- display working environment
ui.clear_screen()
print()
print(f'Broker       : {broker}')
print(f'topic_default: {topic_default}')
print(f'subtopic_root: {subtopic_root}')
print()
print(f'creating new client instance {instance}')
client = mqtt.Client(instance)
print(f'connecting to broker at {broker}')
client.connect(broker)
while True:                # loop
    # ---- get ueser input and verify it
    print()
    s = ui.get_user_input('Enter topic + value: ')
    if not s:                  # empty string?
        break
    l = replace_commas_and_split(s)
    if len(l) != 2:
        print(f'Error: Bad input {s}')
        continue
    # ---- test if a topic or subtopic was entered?
    if re.search('^/',l[0]):
        tt = l[0]                        # topic
    else:
        tt = f'{subtopic_root}/{l[0]}'   # subtopic
    # ---- publish
    print()
    print(f'publish "{l[1]}" to "{tt}"')
    client.publish(tt,l[1])