/**
 * @file Router.hpp
 * @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/>.
 */

#ifndef ARTIS_FACTORY_ROUTER_HPP
#define ARTIS_FACTORY_ROUTER_HPP

#include "Base.hpp"
#include "ProductionOrder.hpp"

#include <deque>

namespace artis::factory {

struct RouterParameters {
  std::size_t pool_number;
};

class Router : public Dynamics<Router, RouterParameters> {
public:
  struct inputs {
    enum values {
      IN, IN_P = 1000
    };
  };

  struct outputs {
    enum values {
      OUT, OUT_P = 1000
    };
  };

  struct vars {
    enum values {
    };
  };

  Router(const std::string &name, const Context<Router, RouterParameters> &context)
    : Dynamics<Router, RouterParameters>(name, context), _parameters(context.parameters()) {
    input_port({inputs::IN, "in"});
    output_port({outputs::OUT, "out"});
    for (unsigned int i = 0; i < context.parameters().pool_number; ++i) {
      output_port({outputs::OUT_P + i, "out_p" + std::to_string(i)});
      input_port({inputs::IN_P + i, "in_p" + std::to_string(i)});
    }
  }

  ~Router() override = default;

  void dint(const Time & /* t */) override;

  void dext(const Time & /* t */, const Time & /* e */, const Bag & /* bag*/) override;

  void start(const Time & /* t */) override;

  Time ta(const Time & /* t */) const override;

  Bag lambda(const Time & /* t */) const override;

  artis::common::event::Value observe(const Time &t, unsigned int index) const override;

private:
  struct Phase {
    enum values {
      INIT, WAIT, SEND
    };

    static std::string to_string(const values &value) {
      switch (value) {
        case INIT:
          return "INIT";
        case WAIT:
          return "WAIT";
        case SEND:
          return "SEND";
      }
      return "";
    }
  };

  // parameters
  RouterParameters _parameters;

  // state
  Phase::values _phase;
  std::deque<std::unique_ptr<ProductionOrder>> _pending_po;
};

} // namespace artis::factory

#endif