from flask import Blueprint, current_app
import paho.mqtt.client as mqtt
from json import loads
import requests


bp = Blueprint("kds-services", __name__)


def handle_mqtt_connect(mqttc, userdata, flags, rc):
    current_app.logger.info("[KDS] Connected on RC/" + str(rc))
    mqttc.subscribe("/printserver/#", 2)
    pass


def process_new_payload(mosq, userdata, msg):
    content = loads(msg.payload.decode("utf-8"))

    if "format" not in content:
        current_app.logger.info(content)
        apiUrl = "%s:%s%s" % (
            current_app.config["KDS_API_SERVER"],
            current_app.config["KDS_API_PORT"],
            current_app.config["KDS_API_URL"],
        )

        response = requests.post("http://%s" % (apiUrl), json=content)
        if response.status_code != 200:
            current_app.logger.error(response.text)
    else:
        pass


@bp.cli.command("listen")
def listen_command():
    """
    Reads from Mqtt topic, stores the data and sends it to the display.

    $ flask kds listen
    """
    mqttc = mqtt.Client("kds")

    # Register a message callback for a specific topic
    mqttc.message_callback_add("/printserver/#", process_new_payload)

    # Set the callback that will handle connection events.
    mqttc.on_connect = handle_mqtt_connect

    current_app.logger.info("Mqtt Client [KDS] connecting ...")
    try:
        mqttc.connect(
            current_app.config["MQTT_BROKER_URL"],
            current_app.config["MQTT_BROKER_PORT"],
            current_app.config["MQTT_KEEPALIVE"],
        )
        current_app.logger.info("Mqtt Client [KDS] connected!")
    except Exception as ex:
        current_app.logger.error(ex)

    mqttc.loop_forever()
