/*------------------------------------------------------------------------------
 src/lib/dj/dbg.cxx
 
 Copyright (c) 2004-2006 Darby Johnston.
 All rights reserved.
 Use is subject to license terms.
------------------------------------------------------------------------------*/

#include "djDbg.h"
#include <djSerialize.h>
#include <stdio.h>

namespace dj {

// XXX Static variables.
//
int Dbg::_print = 0;
static Str _indent;

Dbg::Dbg()
{}

Dbg::Dbg(const char * in)
{
  *this << BEGIN << in << END;
  begin();
}

Dbg::Dbg(const Str & in)
{
  *this << BEGIN << in << END;
  begin();
}

Dbg::~Dbg()
{
  end();
}

void Dbg::begin()
{
  if (! _print) return;
  *this << BEGIN << "{" << END;
  _indent += Str("  ");
}

void Dbg::end()
{
  if (! _print) return;
  _indent.size(_indent.size() - 2);
  _timer.check();
  *this <<
    BEGIN <<
    "} (" << _timer.seconds() << " seconds, " << _timer.fps() << " fps)" <<
    END;
}

void Dbg::operator ++ () { begin(); }
void Dbg::operator -- () { end(); }

Dbg & Dbg::operator << (LINE in)
{
  if (! _print) return *this;
  switch (in) {
    case BEGIN: _tmp = Str("DEBUG ") + _indent; break;
    case END: printf("%s\n", _tmp.toAscii()); break;
  }
  return *this;
}

Dbg & Dbg::operator << (const char * in) { add(Str(in)); return *this; }
Dbg & Dbg::operator << (const Str & in) { add(in); return *this; }

void Dbg::add(const Str & in) { _tmp += in; }

Dbg & operator << (Dbg & dbg, bool in)
{
  return dbg << deflateStr(in);
}

Dbg & operator << (Dbg & dbg, const StrList & in)
{
  return dbg << join(in, Str(" "));
}

const Str dbgBits(uint32_t in)
{
  Str out;
  for (int i = 0; i < 32; ++i)
    out += ((in >> i) & 1) ? '1' : '0';
  return out;
}

const Str dbgBits(float in)
{
  uint32_t * p = (uint32_t *)&in;
  Str out;
  for (int i = 0; i < 32; ++i)
    out += ((*p >> i) & 1) ? '1' : '0';
  return out;
}

}
