// src/backend/holt_graph.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/holt_graph.hh>

#include <sgpemv2/history.hh>
#include <sgpemv2/process.hh>
#include <sgpemv2/thread.hh>

using namespace sgpem;
using namespace std;

void
HoltGraph::update(const History& changed_history)
{
  const Environment& env = changed_history.get_last_environment();
  const Environment::Processes& processes = env.get_processes();

  _resources.clear();
  _active_threads.clear();
  _active_requests.clear();

  for (unsigned int pi = 0; pi < processes.size(); ++pi)
  {
    vector<Thread*> threads = processes[pi]->get_threads();

    for (unsigned int ti = 0; ti < threads.size(); ++ti)
    {
      vector<Request*> requests = threads[ti]->get_requests();

      for (unsigned int ri = 0; ri < requests.size(); ++ri)
      {
        Request& r = *requests[ri];

        if (r.get_state() == Request::state_allocated)
        {
          _active_requests.push_back(&r);
          _active_threads.insert(&r.get_thread());

          vector<SubRequest*> subrequests = r.get_subrequests();

          for (unsigned int sri = 0; sri < subrequests.size(); ++sri)
          {
            Environment::resource_key_t key = subrequests[sri]->get_resource_key();

            _resources.insert(env.get_resources().find(key)->second);
          }
        }
      }
    }
  }
}

HoltGraph::Resources
HoltGraph::get_resources() const
{
  return Resources(_resources.begin(), _resources.end());
}

HoltGraph::Threads
HoltGraph::get_active_threads() const
{
  return Threads(_active_threads.begin(), _active_threads.end());
}

HoltGraph::Requests
HoltGraph::get_active_requests() const
{
  return _active_requests;
}

