#include "Kernel.h"

namespace BlueCore
{

Kernel::Kernel() :
  _Changed(true), _Clear(false)
{
}

void Kernel::addTask(KernelTask* task, int priority)
{
  _AddedTasks.push_back(KernelTaskContainer (task, priority));
  _Changed = true;
}

void Kernel::removeTask(KernelTask* task)
{
  _RemovedTasks.push_back(task );
  _Changed = true;
}

void Kernel::removeAllTasks()
{
  _Clear = true;
}

void Kernel::setTaskPriority(KernelTask* task, int priority)
{
  std::list<KernelTaskContainer>::iterator i;
  for (i = _Tasks.begin(); i != _Tasks.end(); i++)
  {
    if ((*i)._Task.get() == task)
    {
      (*i)._Priority = priority;
      _Changed = true;
      return;
    }
  }

}

bool Kernel::tick()
{
  if (_Changed)
  {
    std::list<KernelTaskContainer>::iterator i;
    for (i = _AddedTasks.begin(); i != _AddedTasks.end(); i++)
    {
      _Tasks.push_back( *i );
    }

    _AddedTasks.clear();
    _RemovedTasks.clear();
    _Tasks.sort();
    _Changed = false;
  }

  std::list<KernelTaskContainer>::iterator i = _Tasks.begin();
  std::list<KernelTaskContainer>::iterator end = _Tasks.end();

  if (i == end)
    return false;

  while (i != end)
  {
    if ((*i)._Task.valid())
      (*i)._Task->tick();
    i++;
  }

  if (_Clear)
  {
    _Tasks.clear();
    _Clear = false;
  }

  return true;
}

} // namespace BlueCore

