//=============================================================================
#include "percentBar.h"

#include <stdio.h>

percentBar::percentBar()
  : asPercent_(false), totalCharLen_(50), currCharLen_(0), msgCharLen_(30),
    showPercent_(false)
{
}

percentBar::percentBar( const char *progressMsg )
  : asPercent_(false), totalCharLen_(50), currCharLen_(0), msgCharLen_(30),
    showPercent_(false)
{
  progressBarMsg( progressMsg );
}

percentBar::~percentBar()
{
}

void
percentBar::progressBarMsg( const char *msg )
{
  // Single char at a time output only works if we turn off buffering
  asPercent_ = false;
  showPercent_=true;
  currCharLen_=0;
  setvbuf(stdout,0,_IONBF,0);
  printf( "%*c", msgCharLen_, ' ' );
  printf( "0%%" );
  for ( int length=totalCharLen_-6, mid=length/2; length>0; length-- )
  {
    if ( length==mid )
      printf("!");
    else
      printf(".");
  }
  printf( "100%%\n" );
  printf( "%*s", msgCharLen_, msg );
}

void 
percentBar::updatePercent( float percent )
{
  if (!showPercent_) return;
  if ( asPercent_ )
  {
    printf("\n %3i%%", (int)(percent*100.0f) );
  }
  else
  {
    int shouldBe = percent*totalCharLen_;
    if ( shouldBe>currCharLen_ )
    {
      for ( int i=shouldBe-currCharLen_; i>0; i-- )
      {
	printf("|");
      }
      currCharLen_ = shouldBe;
    }
  }
}

void 
percentBar::endProgressBar()
{
  updatePercent(1);
  if (!showPercent_) return;
  showPercent_=false;
  printf("\n");
  setvbuf(stdout,0,_IOLBF,0);
  showPercent_=false;
}

void 
percentBar::postWarning( const char *msg )
{
  printf( "Warning: %s", msg );
  asPercent_ = true;
}

void 
percentBar::postError  ( const char *msg )
{
  printf( "ERROR: %s", msg );
  asPercent_ = true;
}

void 
percentBar::postInfo   ( const char *msg )
{
  printf( msg );
  asPercent_ = true;
}
