// src/backend/resource_policy_lifo.cc - Copyright 2005, 2006, University
//               of Padova, dept. of Pure and Applied
//               Mathematics
//
// This file is part of SGPEMv2.
//
// This 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 2 of the License, or
// (at your option) any later version.
//
// SGPEMv2 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 SGPEMv2; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

#include <sgpemv2/resource_policy_lifo.hh>


using namespace std;
using namespace sgpem;

ResourcePolicyLiFo::~ResourcePolicyLiFo()
{}


PolicyParameters&
ResourcePolicyLiFo::get_parameters()
{
  return _parameters;
}

void
ResourcePolicyLiFo::configure()
 throw(UserInterruptException)
{
}

void
ResourcePolicyLiFo::enforce(Environment& environment, Environment::SubRequestQueue& queue, SubRequest& sr)
 throw(UserInterruptException)
{
  typedef Environment::SubRequestQueue SubRequestQueue;

  // the last inserted request goes on the first free place.
  SubRequestQueue old_queue(queue);
  queue.clear();

  typedef SubRequestQueue::iterator It;
  for (It i = old_queue.begin(); i != old_queue.end(); i++)
  {
    // allocated ones remain allocated
    if((**i).get_state() == Request::state_allocated)
      queue.push_back(*i);
  }



  bool inserted = false;
  typedef SubRequestQueue::iterator It;
  for (It i = old_queue.begin(); i != old_queue.end(); i++)
  {
    // allocated ones remain allocated
    if((**i).get_state() != Request::state_allocated)
    {
      // non-allocated ones go after the newly arrived
      if(!inserted)
      {
        queue.push_back(&sr);
        inserted = true;
      }
      if (*i != &sr)
        queue.push_back(*i);
    }
  }
}

Glib::ustring
ResourcePolicyLiFo::get_description() const
{
  return "A resource policy which allows a request to be immediately allocated if there is enough space.";
}

Glib::ustring
ResourcePolicyLiFo::get_name() const
{
  return "Last In, First Out";
}


void
ResourcePolicyLiFo::activate()
{
}

void
ResourcePolicyLiFo::deactivate()
{
}
