"""
 A bridge between APRS messaging and MQTT, designed to control my lora_aprs_node_pico
 
 (C)2022 M.T. Konstapel https://meezenest.nl/mees

 This file is part of aprs-mqtt-bridge.
                                                                                
    aprs-mqtt-bridge is free software: you can redistribute it and/or modify   
    it under the terms of the GNU General Public License as published by        
    the Free Software Foundation, either version 3 of the License, or           
    (at your option) any later version.                                         
                                                                                
    aprs-mqtt-bridge is distributed in the hope that it will be useful,        
    but WITHOUT ANY WARRANTY; without even the implied warranty of              
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               
    GNU General Public License for more details.                                

    You should have received a copy of the GNU General Public License           
    along with aprs-mqtt-bridge. If not, see <https://www.gnu.org/licenses/>.  
"""
import sys
import random
import time
import config_with_yaml as config
from paho.mqtt import client as mqtt_client

configuration_file = "aprs-mqtt-bridge.yml"

# This is where we keep our settings
class mqtt_settings:
    pass
mqtt = mqtt_settings()

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)
    # Set Connecting Client ID
    client = mqtt_client.Client(mqtt.client_id)
    #client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(mqtt.broker, mqtt.port)
    return client

def publish(client, topic, message):
    result = client.publish(topic, message)
    status = result[0]
    if status == 0:
        print(f"Send `{message}` to topic `{topic}`")
    else:
        print(f"Failed to send message to topic {topic}")
        
def subscribe(client: mqtt_client, topic):
    def on_message(client, userdata, message):
        print(f"Received `{message.payload.decode()}` from `{message.topic}` topic")

    client.subscribe(topic)
    client.on_message = on_message

def read_config():
    try:
        cfg = config.load(configuration_file)
    except:
        print ("Configuration file ./" + configuration_file + " not found.")
        sys.exit(1)
    try:
        mqtt.broker = cfg.getProperty("global.broker")
    except:
        print ("Error in configuration file: no broker defined.")
        sys.exit(1)
    try:
        mqtt.port = cfg.getPropertyWithDefault("global.port", 1883)
    except:
        print ("Error in configuration file: no port defined.")
        sys.exit(1)
    try:
        mqtt.topic = cfg.getPropertyWithDefault("global.topic", "aprs-mqtt-bridge")
    except:
        print ("Error in configuration file: no topic defined.")
        sys.exit(1)
    try:
        mqtt.transmit_rate = cfg.getPropertyWithDefault("global.transmit_rate", 30)
    except:
        print ("Error in configuration file: no transmit_rate defined.")
        sys.exit(1)
    try:
        mqtt.retry = cfg.getPropertyWithDefault("global.retry", 3)
    except:
        print ("Error in configuration file: no retry defined.")
        sys.exit(1)
        
    mqtt.client_id = f'{mqtt.topic}-{random.randint(0, 1000)}'

    print (mqtt.broker)
    print (mqtt.topic)
    print (mqtt.port)
    print (mqtt.client_id)
    print (cfg)

def run():
    read_config()
    
    client = connect_mqtt()
    topic = mqtt.topic + '/set'
    subscribe(client,topic)
    client.loop_start()
    while True:
        time.sleep(1)
        topic = mqtt.topic + '/result'
        publish(client,topic,'test')

if __name__ == '__main__':
    run()
