#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package Common::TextProgressBar;
use strict;
use warnings;

use FileHandle;

use constant kBarSize => 40;

sub new {
    my ( $class, $max, $quanta ) = @_;

    my $self = bless {}, $class;

    $self->{_max} = $max;

    $self->{_startTime} = time;
    $self->{_lastTime}  = time;
    $self->{_iteration} = 0;
    $self->{_quanta}    = ( $quanta ? $quanta : 1 );

    return $self;
}

sub increment {
    my ($self) = @_;

    $self->{_iteration}++;
    $self->{_lastTime} = time;
}

sub display {
    my ( $self, $fh ) = @_;

    my $chunk = $self->{_iteration} % $self->{_quanta};

    return unless 0 == $chunk;

    my $fractionComplete = $self->{_iteration} / $self->{_max};

    # calculate estimated time remaining
    #
    my $displayTimeLeft = "??:??:??";
    my $timeSpent       = $self->{_lastTime} - $self->{_startTime};
    my $estTotalTime    = "??:??:??";
    if ($fractionComplete) {
        $estTotalTime = $timeSpent * ( 1 / $fractionComplete );
    }
    my $timeLeft = $estTotalTime - $timeSpent;

    if ( $timeLeft > 0 ) {
        $displayTimeLeft = _secondsToString($timeLeft);
    }

    my $displayTimeElapsed = _secondsToString($timeSpent);

    my $barSize = int( kBarSize * $fractionComplete );
    my $bar     = '=' x $barSize;
    $bar .= '>';
    $bar .= ' ' x ( kBarSize - $barSize );

    # JPK - The output stream needs to be set to autoflush for this to work...
    # I'm not sure I want to do that here, though...
    #
    $fh->autoflush(1);
    print "\relapsed:$displayTimeElapsed  remaining:$displayTimeLeft [$bar] : "
      . $self->{_iteration} . " / "
      . $self->{_max}
      . "                ";
    $fh->autoflush(0);
}

sub _secondsToString {
    my ($time) = @_;

    my ( $h, $m, $s );
    if ( $time >= 3600 ) {
        $h = int( $time / 3600 );
        $time -= ( $h * 3600 );
    }

    if ( $time >= 60 ) {
        $m = int( $time / 60 );
        $time -= ( $m * 60 );
    }

    $s = $time;

    return sprintf( "%02d:%02d:%02d", $h, $m, $s );
}

1;
