// src/backend/resource_policy_priority.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_priority.hh>
#include <sgpemv2/thread.hh>

// FIXME: remove include
#include <iostream>

using namespace std;
using namespace sgpem;

ResourcePolicyPriority::~ResourcePolicyPriority()
{}


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

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

void
ResourcePolicyPriority::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);
  }



  // assume they are ordered by priority.
  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 with lower priority go after the newly arrived
      int pthat = (**i).get_request().get_thread().get_current_priority();
      int pthis = sr.get_request().get_thread().get_current_priority();
      std::cout << "\npthat = " << pthat;
      std::cout << "\npthis = " << pthis;
      if(!inserted &&  pthis <=  pthat)
      {
        queue.push_back(&sr);
        inserted = true;
      }
      if (*i != &sr)
        queue.push_back(*i);
    }
  }
}

Glib::ustring
ResourcePolicyPriority::get_description() const
{
  return "A resource policy which satisfies higher priority requests before lower priority ones.";
}

Glib::ustring
ResourcePolicyPriority::get_name() const
{
  return "Higher Priority First";
}


void
ResourcePolicyPriority::activate()
{
}

void
ResourcePolicyPriority::deactivate()
{
}
