package qosient::util;

use strict;
use Exporter;
use vars qw($VERSION @ISA @EXPORT);
use Time::Local;
use Switch;

$VERSION = "1.00";
@ISA     = qw(Exporter);
@EXPORT  = qw(parsetime);

use Carp;
use warnings;

# parsetime returns a list of the form generated by localtime()
# representing the time string in the first parameter.  If that time is
# an empty string, a list representing yesterday is returned.
sub parsetime {
    my ($time) = @_;

    my @time;
    my ($sec, $min, $hour, $mday, $mon, $year) = localtime();

    if ( !defined $time || $time eq "" ) {
        my $yesterday =
          timelocal( 0, 0, 12, $mday, $mon, $year ) - 24 * 60 * 60;
        @time = localtime($yesterday);

    }
    else {
        my $op = substr( $time, 0, 1 );

        if ( $op eq '-' ) {
            my $value = substr( $time, 1 );
            my $index = substr( $time, -1 );
            if ( $value =~ /(\d+)/ ) {
                $value = $1;
            }
            switch ($index) {
                case 's' { }
                case 'm' { $value *= 60 }
                case 'h' { $value *= 60 * 60 }
                case 'd' { $value *= 24 * 60 * 60 }
                case 'w' { $value *= 7 * 24 * 60 * 60 }
                case 'M' {
                    $mon -= $value;
                    while ( $mon < 0 ) {
                        $year--;
                        $mon += 12;
                    }
                    $value = 0
                }
                case 'y' { $year -= $value; $value = 0 }
                case 'Y' { $year -= $value; $value = 0 }
            }
            my $time =
              timelocal( $sec, $min, $hour, $mday, $mon, $year ) - $value;
            @time = localtime($time);

        }
        else {
            my ( $year, $mon, $mday ) = split( '/', $time );
            my $time = timelocal( 0, 0, 12, $mday, $mon - 1, $year - 1900 );
            @time = localtime($time);
        }
    }
    return @time;
}

1;
