#include <artis-star/common/RootCoordinator.hpp>
#include <artis-star/kernel/pdevs/Coordinator.hpp>
#include <artis-star/kernel/pdevs/GraphManager.hpp>

#include <chrono>
#include <iostream>

#define BOOST_TEST_MODULE Factory_JSON_Tests

#include <boost/test/unit_test.hpp>
#include <artis-star/kernel/pdevs/Simulator.hpp>

#include "FactoryGraphManager.hpp"
#include "Machine.hpp"
#include "PoolRouter.hpp"
#include "ProductionOrderGenerator.hpp"
#include "Router.hpp"

using namespace std::chrono;

class JsonPoolRouterView : public artis::factory::View {
public:
  JsonPoolRouterView(unsigned int pool_number) {
    for (int i = 0; i < (int) pool_number; ++i) {
      selector("PoolRouter_" + std::to_string(i) + ":waiting_po_number",
               {artis::factory::FactoryGraphManager::POOL_ROUTER + i,
                artis::factory::PoolRouter::vars::WAITING_PO_NUMBER});
    }
    selector("Generator:total_po_number",
             {artis::factory::FactoryGraphManager::GENERATOR,
              artis::factory::ProductionOrderGenerator::vars::TOTAL_PO_NUMBER});
  }
};

BOOST_AUTO_TEST_CASE(TestCase_JSONPool)
{
  std::ifstream input("../../data/factory.json");

  if (input) {
    std::string str((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());
    artis::factory::JsonReader reader;

    reader.parse(str);

    artis::factory::FactoryGraphManagerParameters graph_parameters{reader.factory()};
    artis::common::context::Context<artis::common::DoubleTime> context(0, 8 * 3600); // 8h
    artis::common::RootCoordinator<
      artis::common::DoubleTime, artis::pdevs::Coordinator<
        artis::common::DoubleTime, artis::factory::FactoryGraphManager, artis::common::NoParameters, artis::factory::FactoryGraphManagerParameters>
    > rc(context, "root", artis::common::NoParameters(), graph_parameters);

    rc.attachView("PoolRouter", new JsonPoolRouterView(reader.factory()._pools.size()));
    rc.switch_to_timed_observer(1);

    steady_clock::time_point t1 = steady_clock::now();

    rc.run(context);

    steady_clock::time_point t2 = steady_clock::now();

    duration<double> time_span = duration_cast<duration<double> >(t2 - t1);

    std::cout << "Duration: " << time_span.count() << std::endl;

    artis::factory::Output output(rc.observer());

    output(context.begin(), context.end(), {context.begin(), 1});

    std::cout << artis::factory::Trace::trace().elements().filter_level_type(artis::common::LevelType::USER).to_string()
              << std::endl;

    BOOST_CHECK(true);
  } else {
    BOOST_CHECK(false);
  }
}