#pragma once

#include "ITaskListener.h"
#include "BackgroundWorker.h"
#include <boost/unordered_map.hpp>

namespace MP
{
  namespace TaskEventTypes
  {
    enum TaskEventType
    {
      Starting, Ending
    };
  }
  typedef TaskEventTypes::TaskEventType TaskEventType;
  struct PendingTaskEvent
  {
    TaskEvent event;
    TaskEventType type;

    PendingTaskEvent() : type(TaskEventTypes::Starting) {}
    PendingTaskEvent(TaskEvent ev, TaskEventType ty) : event(ev), type(ty) {}
  };

  class StatsRecorder : public ITaskListener, public BackgroundWorker<PendingTaskEvent>
  {
    typedef boost::unordered_map<Task::id_type, TaskEvent> EventMap;
    Task::time_point m_beginTime;
    const size_t m_threadCount;
    mutable EventMap m_events;
    mutable size_t m_tasksCompleted;
    mutable Task::time_span m_longestWaitTime;
    mutable Task::time_span m_totalRunTime;
  protected:
    virtual void handle(const PendingTaskEvent &ev) const;
  public:
    StatsRecorder(size_t threadCount) : m_threadCount(threadCount), m_tasksCompleted(0), m_longestWaitTime(0), m_totalRunTime(0) {}
    ~StatsRecorder();
    void start() 
    { 
      BackgroundWorker::start("Stats Recorder");
      m_beginTime = Task::getCurrentTime();
    }
    virtual void onTaskStarted(const TaskEvent &ev);
    virtual void onTaskEnded(const TaskEvent &ev);
  };
}