package Utils::File;
use Carp;
use warnings;
use strict;


###################################################
sub basename {
    my $filename  = shift or croak "File name is not defined.";
    my $extension = shift;
    if( $extension ){
        open IN, "basename $filename $extension |"
            or die "Can't execute basename command.";
    } else {
        open IN, "basename $filename |"
            or die "Can't execute basename command.";
    }
    my $basename = <IN>;
    chomp $basename;
    close IN;
    return $basename;
}

###################################################
sub getFiles {
    my $dir = shift or croak "Directory name is not specified.";
    my $extensions = shift or croak "Valid extensions are not specified.";
    $dir   .= '/' unless $dir =~ /\/$/;
    my $files = [];
    opendir DIR, $dir or die "Can't open $dir as a directory.";
    while( defined( my $file = readdir(DIR) ) ){
	if( hasValidExtension($file, $extensions) ){
	    push(@$files, $dir.$file);
	}
    }
    closedir DIR;
    return $files;
}

###################################################
sub hasValidExtension {
    my $filename = shift or croak "File name is not specifed.";
    my $extensions = shift or croak "Valid extensions are not specified.";
    foreach my $ext (@$extensions){
	if( $filename =~ /\.$ext$/ ){
	    return 1;
	}
    }
    return 0;
}

###################################################
sub rmExtension {
    my $filename = shift or croak "File name is not specifed.";
    my $extensions = shift or croak "Valid extensions are not specified.";
    foreach my $ext (@$extensions){
	if( $filename =~ /^(.+)$ext$/ ){
	    return $1;
	}
    }
    return 0;
}

###################################################
sub getCurrentDirectory {
    open IN, "pwd | " or die "Can't execute pwd command.";
    my $curDir = <IN>; chomp $curDir;
    $curDir   .= '/' unless $curDir =~ /\/$/;
    close IN;
    return $curDir;
}

1;
