from flask import Blueprint, request, current_app
import paho.mqtt.client as mqtt
from json import dumps, 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"))
    print(content)

    apiUrl = "%s:%s%s" % (
        current_app.config["KDS_API_SERVER"],
        current_app.config["KDS_API_PORT"],
        current_app.config["KDS_API_URL"],
    )

    res = requests.post("http://%s" % (apiUrl), json=content)
    # print (res)

    # if printer == None:
    #     return send_to_printer(default_printer, content)
    # else:
    #     return send_to_printer(printer, content)
    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")

    mqttc.message_callback_add("/printserver/#", process_new_payload)

    # Add message callbacks that will only trigger on a specific subscription match.
    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()
