#include "SiteServer.h"

#include "Things/TemperatureSensor.h"

#if !defined(NO_STD)
#include <functional>
#include <memory>
#endif

namespace RoboidControl {

SiteServer::SiteServer(int port) {
  this->name = "Site Server";
  this->publishInterval = 0;

  this->ipAddress = "0.0.0.0";
  this->port = port;

#if defined(NO_STD)
  this->senders[this->senderCount++] = this;
#else
  this->senders.push_back(this);
#endif

  SetupUDP(port, ipAddress, 0);

#if !defined(NO_STD)
  Register<TemperatureSensor>((unsigned char)Thing::Type::TemperatureSensor);
#endif
}

void SiteServer::Process(Participant* sender, ParticipantMsg* msg) {
  if (msg->networkId == 0) {
    // std::cout << this->name << " received New Client -> " <<
    // sender->ipAddress
    //           << ":" << (int)sender->port << "\n";
    SiteMsg* msg = new SiteMsg(sender->networkId);
    this->Send(sender, msg);
    delete msg;
  }
}

void SiteServer::Process(Participant* sender, SiteMsg* msg) {}

void SiteServer::Process(Participant* sender, ThingMsg* msg) {
  Thing* thing = sender->Get(msg->networkId, msg->thingId);
  if (thing == nullptr) {
#if defined(NO_STD)
    new Thing(sender, msg->networkId, msg->thingId,
              (Thing::Type)msg->thingType);
#else
    auto thingMsgProcessor = thingMsgProcessors.find(msg->thingType);
    Thing* newThing;
    if (thingMsgProcessor != thingMsgProcessors.end())  // found item
      newThing =
          thingMsgProcessor->second(sender, msg->networkId, msg->thingId);
    else
      newThing = new Thing(sender, msg->networkId, msg->thingId,
                           (Thing::Type)msg->thingType);
#endif
  }
}

}  // namespace RoboidControl