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

namespace artis::factory {

void Stock::dint(const Time & /* t */) {
  switch (_phase) {
    case Phase::SEND_AVAILABLE: {
      _available_demands.clear();
      _phase = Phase::WAIT;
      break;
    }
    case Phase::SEND: {
      _demands.clear();
      _phase = Phase::WAIT;
      break;
    }
    case Phase::WAIT: {
      assert(false);
    }
  }
}

void Stock::dext(const Time &t, const Time & /* e */, const Bag &bag) {
  std::for_each(bag.begin(), bag.end(), [t, this](const ExternalEvent &event) {
    if (event.on_port(inputs::IN)) {
      StockEntry entry;

      event.data()(entry);
      if (_parameters._capacity == -1 or (int) _entries.size() < _parameters._capacity) {
        _entries.push_back({t, entry.po_id, entry.po_index, entry.product_id, entry.quantity});
      } else {
        assert(false);
      }
    } else if (event.port_index() >= inputs::IN_DEMAND and event.port_index() < inputs::IN_STOCK_AVAILABLE) {
      ProductDemand demand;

      event.data()(demand);
      auto it = std::find_if(_entries.begin(), _entries.end(), [demand](const auto &e) {
        return e._po_id == demand.po_id and e._po_index == demand.po_index and e._product_id == demand.product_id
               and e._quantity >= demand.quantity;
      });

      if (it != _entries.end()) {
        if (it->_quantity == demand.quantity) {
          _entries.erase(it);
        } else {
          it->_quantity -= demand.quantity;
        }
        _demands.push_back(std::make_pair(event.port_index() - inputs::IN_DEMAND, demand));
        _phase = Phase::SEND;
      }
    } else if (event.port_index() >= inputs::IN_STOCK_AVAILABLE) {
      unsigned int machine_id = event.port_index() - inputs::IN_STOCK_AVAILABLE;
      unsigned int po_id;

      event.data()(po_id);
      _available_demands.push_back(AvailableDemand{machine_id, po_id, false});
      if (_parameters._capacity == -1 or (int) _entries.size() < _parameters._capacity) {
        auto it = std::find_if(_waiting_machine_ids.begin(), _waiting_machine_ids.end(),
                               [machine_id, po_id](const auto &e) {
                                 return machine_id == e.first and po_id == e.second;
                               });

        if (it != _waiting_machine_ids.end()) {
          _waiting_machine_ids.erase(it);
        }
        _available_demands.back()._available = true;
        _phase = Phase::SEND_AVAILABLE;
      } else {
        _waiting_machine_ids.push_back(std::make_pair(machine_id, po_id));
        _phase = Phase::SEND_AVAILABLE;
      }
    }
  });
}

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

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

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

  if (_phase == Phase::SEND) {
    for (const auto &e: _waiting_machine_ids) {
      bag.push_back(ExternalEvent(outputs::OUT_STOCK_AVAILABLE + e.first,
                                  StockAvailableResponse(e.second, StockAvailableResponse::NEW_AVAILABLE)));
    }
    for (const auto &e: _demands) {
      bag.push_back(ExternalEvent(outputs::OUT + e.first, ProductResponse(e.second.product_id, e.second.po_id)));
    }
  } else if (_phase == Phase::SEND_AVAILABLE) {
    for (const auto &demand: _available_demands) {
      bag.push_back(ExternalEvent(outputs::OUT_STOCK_AVAILABLE + demand._machine_id,
                                  StockAvailableResponse(demand._po_id,
                                                         demand._available ? StockAvailableResponse::AVAILABLE
                                                                           : StockAvailableResponse::NOT_AVAILABLE)));
    }
  }
  return bag;
}

artis::common::event::Value Stock::observe(const Time & /* t */, unsigned int index) const {
  switch (index) {
    case vars::ENTRY_NUMBER:
      return (unsigned int) _entries.size();
  }
  return {};
}

} // namespace artis::factory