package progress_bar;

use warnings;
use strict;

use Time::HiRes qw/time/;
use Data::Dump qw/dump/;

our $start_t;
our $last_t;

sub start {
	$start_t = $last_t = time();
}

sub tick {
	die "arguments wrong: ",dump( @_ ) unless $#_ == 2;
	my ($file, $pos, $size) = @_;

	return unless $size;

	my $t = time();
	return unless	$start_t == $last_t
				||	$pos == $size
				||	$t - $last_t > 0.75 # s
				;

	$last_t = $t;
	$t -= $start_t;
	return unless $t;

	my $speed = $pos / $t;
	return unless $speed;

	printf STDERR "%s %d/%d %.2f%% %.2f K/s ETA %.1fs   \r"
		, $file, $pos, $size
		, $pos * 100 / $size
		, $speed / 1024
		, ( $size - $pos ) / $speed
		;
}

1;
