#include "SimCore/UtilFunctions.hpp"
#include <Orders/MoveOrder.hpp>
#include <cstdlib>
#include <iostream>
#include <csignal>

#include <SimControl/SimControl.hpp>
#include <loguru.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;
  }
}



int main()
{

// setup signal handler
    struct sigaction sigIntHandler;
    sigIntHandler.sa_handler = killHandlerPing;
    sigemptyset(&sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;
    sigaction(SIGINT, &sigIntHandler, NULL);

    bool online = false;

    const char* CommandPortChar = "5555";
    if (std::getenv("COMMAND_PORT") != nullptr) {
          CommandPortChar = std::getenv("COMMAND_PORT");
    }
    const char* GroundTruthAddr = "239.0.0.1";
    if (std::getenv("GROUNDTRUTH_ADDR") != nullptr) {
          GroundTruthAddr = std::getenv("GROUNDTRUTH_ADDR");
    }
    const char* GroundTruthPort = "10000";
    if (std::getenv("GROUNDTRUTH_PORT") != nullptr) {
          GroundTruthPort = std::getenv("GROUNDTRUTH_PORT");
    }

    const char* Namespace = "simulator";
    if (std::getenv("NAMESPACE") != nullptr) {
          Namespace = std::getenv("NAMESPACE");
          online = true;
    }


    const char *ServerAddress = nullptr;

    ServerAddress = std::getenv("SERVER_IP");
    if (ServerAddress == nullptr) {
      ServerAddress = "127.0.0.1";
    }

    LOG_S(INFO)<<ServerAddress;

    LOG_S(INFO)<<"online:" << online;

    LOG_S(INFO)<< "command port"<< CommandPortChar;

    SimControl::SimControl sc(online,CommandPortChar,GroundTruthAddr,SimCore::UtilFunctions::StringToUShort(GroundTruthPort),Namespace);


    while (running) {

      std::this_thread::sleep_for(std::chrono::milliseconds(500));
    } 

    sc.stop();

    LOG_S(INFO)<<"end app";
    std::this_thread::sleep_for(std::chrono::milliseconds(300));
    return 0;
    // std::exit(0);
}