#include "WHISPER/Messages/Message.hpp"
#include "zmq.hpp"
#include <iostream>
#include <loguru.hpp>

#include <memory>
#include <thread>

#include <WHISPER/InternalUDPService.hpp>
#include <WHISPER/Messages/Join.hpp>
#include <WHISPER/Messages/Leave.hpp>



/// variable for stopping the application
bool running = true;

/**
 * @brief killhandler to set running to false on CTRL-C
 * 
 * @param s - the signal to manage
 */
void killHandlerPing(int s) {

  if (s == SIGINT) {
    running = false;
  }
}

#define ID 2
int main()
{
     
// setup signal handler
    struct sigaction sigIntHandler;
    sigIntHandler.sa_handler = killHandlerPing;
    sigemptyset(&sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;
    sigaction(SIGINT, &sigIntHandler, NULL);

    // zmq::context_t ctx(2);
    // zmq::socket_t sock(ctx,zmq::socket_type::dish);
    // sock.bind("udp://*:8000");
    // zmq::message_t temp;
    // sock.join("data");



    auto receiver = std::make_shared<WHISPER::threadSafeQueue<WHISPER::Message>>();
    WHISPER::InternalUDPService service(2,WHISPER::SHIP,8000,"192.168.0.255","192.168.1.178");
    
    service.subscribe(WHISPER::MsgTopicsMap[WHISPER::MsgTopics::TRACK]);
    service.subscribe(WHISPER::MsgTopicsMap[WHISPER::MsgTopics::DATA]);

    // WHISPER::Join join(2,1,WHISPER::SourceType::SHIP,8000,"192.168.1.178");
    // service.publish(join.serialize(),WHISPER::MsgTopicsMap[WHISPER::MsgTopics::MANAGEMENT]);

    service.connect(receiver);

    // zmq::context_t ctx(2);
    // zmq::socket_t sock(ctx,zmq::socket_type::radio);
    // sock.connect("udp://127.0.0.1:8000");
    // std::string string = "hello world form 2";

    int msgcount = 0;

     while (running) {  
      if (msgcount !=  receiver->size()) {
          LOG_S(INFO)<<"received messages " << receiver->size();

        auto received =  receiver.get()->get();
        auto topic = received.topic_;
        LOG_S(INFO)<<"message type is: "<<received.msgType_;
        if (received.msgType_ == WHISPER::RAW_TRACK) {


        }
          msgcount = receiver->size();

        // service.publish(received.serialize(), WHISPER::MsgTopicsMap[(WHISPER::MsgTopics)topic]);
      }
     
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
    } 
    // WHISPER::Leave leave(2,WHISPER::SourceType::SHIP,8000,"192.168.1.178");
    // service.publish(leave.serialize(), WHISPER::MsgTopicsMap[WHISPER::MsgTopics::MANAGEMENT]);

    // LOG_S(INFO)<<"message send";

    service.disconnect();
return 0;
}