#include "Profiler.h"

#ifdef ENABLE_PROFILER

// static fields.
Profiler* const Profiler::BYTECODE_PROFILER = new Profiler(_T("BC"), 256);
Profiler* const Profiler::UNZIP_SEEK_PROFILER = new Profiler(_T("UnzipSeek"), 1);

Profiler::Profiler(_TCHAR* name, unsigned int numOfSlots) : numberOfSlots(numOfSlots)
{
  assert(name);
  assert(numOfSlots > 0);
  size_t len = _tcslen(name);
  this->name = new _TCHAR[len + 1];
  _tcscpy(this->name, name);

  this->slots = new ProfilerSlot[numOfSlots];
}

void Profiler::writeTo(HANDLE hFile)
{
  _TCHAR buff[128];
  DWORD numOfWritten;
  for (unsigned int i = 0; i < this->numberOfSlots; ++i)
  {
    _stprintf(buff, _T("%ld,%ld\n"), this->slots[i].count, this->slots[i].elapsed);
    size_t len = _tcslen(buff);
    WriteFile(hFile, buff, sizeof(_TCHAR) * len, &numOfWritten, NULL);
  }
}

void Profiler::writeAllProfiles()
{
  // write bytecode profiler.
  Profiler* profiler = Profiler::BYTECODE_PROFILER;
  HANDLE hFile = CreateFile(_T("\\bytecode.profiler"), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  profiler->writeTo(hFile);
  CloseHandle(hFile);

  // write unzip seek profiler
  profiler = Profiler::UNZIP_SEEK_PROFILER;
  hFile = CreateFile(_T("\\unzip_seek.profiler"), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  profiler->writeTo(hFile);
  CloseHandle(hFile);

}


#endif