#include "include/websocket.h"

namespace germanairlinesva
{
namespace websocket
{
  Websocket::Websocket(std::string host,
                       std::string user,
                       std::function<void(const std::string)> toLog)
      : host(host), user(user), toLog(std::move(toLog))
  {
#ifdef IBM
    // Required on Windows
    ix::initNetSystem();
#endif

    this->webSocket = new ix::WebSocket();
    this->webSocket->enableAutomaticReconnection();
    this->webSocket->setUrl(host);
    this->webSocket->setOnMessageCallback(
        [this](const ix::WebSocketMessagePtr &msg) {
          this->onClientMessageCallback(msg);
        });
    this->webSocket->start();
  }

  Websocket::~Websocket()
  {
    this->webSocket->stop();
    this->toLog("WebSocket stopped");
#ifdef IBM
    // Required on Windows
    ix::uninitNetSystem();
#endif
  }

  void Websocket::onClientMessageCallback(const ix::WebSocketMessagePtr &msg)
  {
    if (msg->type == ix::WebSocketMessageType::Open) {
      std::stringstream debug_msg;

      debug_msg << std::endl << "New connection" << std::endl;
      debug_msg << "Uri: " << msg->openInfo.uri << std::endl;
      debug_msg << "Headers:" << std::endl;
      for (const auto &it : msg->openInfo.headers) {
        debug_msg << it.first << ": " << it.second << std::endl;
      }

      this->toLog(debug_msg.str());

      this->webSocket->send("MASTER:" + user);
      this->toLog("Connecting as " + user);
    } else if (msg->type == ix::WebSocketMessageType::Close) {
      if (msg->closeInfo.reason.compare("DUPLICATE") == 0) {
        this->webSocket->disableAutomaticReconnection();

        this->toLog("Disconnected due to beeing a duplicate simualtor");
      } else {
        std::stringstream debug_msg;

        debug_msg << std::endl << "Connection closed" << std::endl;
        debug_msg << "Code: " << msg->closeInfo.code << std::endl;
        debug_msg << "Reason: " << msg->closeInfo.reason << std::endl;
        debug_msg << "Remote: " << msg->closeInfo.remote << std::endl;

        this->toLog(debug_msg.str());
      }
    } else if (msg->type == ix::WebSocketMessageType::Error) {
      std::stringstream debug_msg;

      debug_msg << std::endl << "Connection error" << std::endl;
      debug_msg << "Decompression: " << msg->errorInfo.decompressionError
                << std::endl;
      debug_msg << "HTTP status: " << msg->errorInfo.http_status << std::endl;
      debug_msg << "Reason: " << msg->errorInfo.reason << std::endl;
      debug_msg << "Retries: " << msg->errorInfo.retries << std::endl;
      debug_msg << "Wait time: " << msg->errorInfo.wait_time << std::endl;

      this->toLog(debug_msg.str());
    } else if (msg->type == ix::WebSocketMessageType::Message) {
      if (!msg->str.empty()) {
        this->toLog(msg->str);
      }
    }
  }

  void Websocket::sendData(data &d)
  {
    if (strcmp(d.path, this->lastPath) != 0) {
      strcpy(this->lastPath, d.path);
      if (util::generateMD5(d.path, this->lastHash, this->toLog)) {
        strcpy(this->lastHash, "NOT SET");
      }
    }

    nlohmann::json json = {
        {"altitude", d.alt},
        {"vs", d.vs},
        {"ias", d.ias},
        {"magHdg", d.magHeading},
        {"truHdg", d.truHdg},
        {"totFuel", d.totFuelKg},
        {"fuelFlow", d.ff},
        {"hash", this->lastHash},
    };

    if (this->webSocket != nullptr) {
      std::ostringstream msg;
      msg << "SEND:" << user << ":" << json.dump();
      this->webSocket->send(msg.str(), false);
    }
  }
} // namespace websocket
} // namespace germanairlinesva