#include "config.h"
#include "WiFiNet.h"
#include "Sprocket.h"
#include "MqttPlugin.h"

const char* mqChatTopic = "wirelos/chat/log";
const char* outChatTopic = "out/chat/log";
const char* chatUser = "user";

WiFiNet *network;
Sprocket *sprocket;
MqttPlugin *mqttPlugin;

Task publishHeap;

void setup()
{

    sprocket = new Sprocket({STARTUP_DELAY, SERIAL_BAUD_RATE});
    mqttPlugin = new MqttPlugin({"chatSprocket",
                                 "192.168.1.2",
                                 1883,
                                 "wirelos/sprocket"},
                                true, true);                            
    sprocket->addPlugin(mqttPlugin);

    // this subscription gets shadowed by the MqttPlugin
    // to rout messages to the queue on topic wirelos/sprocket/chat/log
    //sprocket->subscribe("chat/log", [](String msg) {
    //    // gets routed to MQTT broker
    //    PRINT_MSG(Serial, "CHAT", msg.c_str());
    //});
    publishHeap.set(TASK_SECOND * 5, TASK_FOREVER, []() {
        sprocket->publish(outChatTopic, "hi there");
    });
    sprocket->addTask(publishHeap);

    network = new WiFiNet(
        SPROCKET_MODE,
        STATION_SSID,
        STATION_PASSWORD,
        AP_SSID,
        AP_PASSWORD,
        HOSTNAME,
        CONNECT_TIMEOUT);
    network->connect();

    sprocket->subscribe("mqtt/connect", [](String msg) {
        if (msg.length() > 0)
        {
            mqttPlugin->client->subscribe(mqChatTopic);
            sprocket->subscribe(mqChatTopic, [](String msg) {
                PRINT_MSG(Serial, "CHAT", String("incoming:  " + msg).c_str());
                //webApiPlugin->ws->textAll(msg);
            });

            // send message from WS to this topic
            sprocket->subscribe(outChatTopic, [](String msg) {
                PRINT_MSG(Serial, "CHAT", msg.c_str());
                mqttPlugin->client->publish(mqChatTopic, (String(chatUser) + ": " + msg).c_str());
            });
        }
    });

    sprocket->activate();

}

void loop()
{
    sprocket->loop();
    yield();
}