package Common::Time;

use strict;
use warnings;

use Date::Parse;
use Exporter;

our @ISA = qw(Exporter);
our @EXPORT = qw(whattime whatday get_now_time_str get_time_diff_str convert_datestr2datetime);

## +3 GMT Russian time zone offset
## +2 GMT Bulgarian time zone offset
use constant TIME_ZONE_RU_OFFSET => 3;
use constant TIME_ZONE_BG_OFFSET => 2;
use constant TIME_ZONE_DEFAULT_OFFSET => TIME_ZONE_BG_OFFSET;

## XXX: all dates are in russian date format, not in internation!


sub whattime{
   my $time=shift;
   $time=time() unless($time);
   my ($sc,$mn,$hr,$d,$m,$y,$wday,$yday,$isdst) = localtime($time);
   $hr="0".$hr if ($hr<10);
   $mn="0".$mn if ($mn<10);
   $sc="0".$sc if ($sc<10);
   return ($hr,$mn,$sc);
}

sub whatday{
   my $time=shift;
   $time=time() unless($time);
   my ($sec,$min,$hour,$d,$m,$y,$wday,$yday,$isdst) = localtime($time);
   $y+=1900;
   $m++;
   $m="0".$m if ($m<10);
   $d="0".$d if ($d<10);
   return ($d,$m,$y);
}

sub get_now_time_str {
	my ($DD,$MM,$YY) = whatday();
	my ($HR,$MN,$SC) = whattime();
    return ("$DD.$MM.$YY $HR:$MN:$SC");
}

sub get_time_diff_str {
	my $start_time = shift or die "Start time should be given!";
	my $end_time = shift;
	$end_time = time()
		unless $end_time;
	
	my $diff_time = $end_time - $start_time;
	my $uptime_str = '';

	## calc full days
	my $days = int( $diff_time / 86400 );
	$diff_time -= $days * 86400;

	## calc full hours
	my $hours = int( $diff_time / 3600 );
	$diff_time -= $hours * 3600;

	## calc full minutes
	my $minutes = int( $diff_time / 60 );
	$diff_time -= $minutes * 60;

	## calc seconds
	my $seconds = $diff_time;

	$uptime_str .= "$days days "
		if( $days );
	$uptime_str .= "$hours hours "
		if( $hours || $days );
	$uptime_str .= "$minutes min. "
		if( $minutes || $hours || $days );
	$uptime_str .= "$seconds sec. "
		if( $seconds || $minutes || $hours || $days );

	return $uptime_str;
}

## converts date from 'Fri, 28 Jan 2005 19:12:04 +0000' into YYYY-MM-DD HR:MN:SC
sub convert_datestr2datetime {
	my $datestr = shift or die("Date string should be specified!");

	my $time = str2time($datestr, TIME_ZONE_DEFAULT_OFFSET*3600);
	return undef
		unless($time);

	my @date = localtime($time);

	return sprintf("%04d-%02d-%02d %02d:%02d:%02d",1900+$date[5],$date[4]+1,$date[3],$date[2],$date[1],$date[0]);
}


1;
