/**
 * @file Router.cpp
 * @author The ARTIS Development Team
 * See the AUTHORS or Authors.txt file
 */

/*
 * ARTIS - the multimodeling and simulation environment
 * This file is a part of the ARTIS environment
 *
 * Copyright (C) 2013-2023 ULCO http://www.univ-littoral.fr
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Router.hpp"

namespace artis::factory {

void Router::dint(const Time & /* t */) {
  switch (_phase) {
    case Phase::INIT: {
      _phase = Phase::WAIT;
      break;
    }
    case Phase::WAIT: {
      break;
    }
    case Phase::SEND: {
      _pending_po.pop_front();
      if (not _pending_po.empty()) {
        _phase = Phase::SEND;
      } else {
        _phase = Phase::WAIT;
      }
      break;
    }
  }
}

void Router::dext(const Time & /* t */, const Time & /* e */, const Bag &bag) {
  std::for_each(bag.begin(), bag.end(), [this](const common::event::ExternalEvent<common::DoubleTime> &event) {
    if (event.port_index() >= inputs::IN) {
      uint8_t *data = nullptr;

      event.data()(data);
      _pending_po.push_back(std::make_unique<ProductionOrder>(data, event.data().size()));
      _phase = Phase::SEND;
    }
  });
}

void Router::start(const Time & /* t */) {
  _phase = Phase::INIT;
}

Time Router::ta(const Time & /* t */) const {
  switch (_phase) {
    case Phase::INIT:
      return 0;
    case Phase::WAIT:
      return artis::common::DoubleTime::infinity;
    case Phase::SEND:
      return 0;
  }
  return artis::common::DoubleTime::infinity;
}

Bag Router::lambda(const Time & /* t */) const {
  Bag bag;

  if (_phase == Phase::SEND) {
    if (not _pending_po.empty()) {
      auto po = _pending_po.front().get();

      if (not po->is_finish() and po->current_operation().get_type() == CHANGE_POOL_TYPE) {
        bag.push_back(ExternalEvent(outputs::OUT_P + po->current_operation().get_loc_index(),
                                    common::event::Value(po->_buffer, po->_size)));
      } else if (po->is_finish()) {
        bag.push_back(ExternalEvent(outputs::OUT, common::event::Value(po->_buffer, po->_size)));
      } else {
        assert(false);
      }
    }
  }
  return bag;
}

artis::common::event::Value Router::observe(const Time & /* t */, unsigned int /* index */) const {
  return {};
}

} // namespace artis::factory