package Greenstone::Helpers;

use strict;
use warnings;
use utf8;
use File::Copy 'cp';
use base 'Exporter';

our $VERSION = 1.00;
our @EXPORT  = qw(lsfiles empty comment trim escape hashdump);

sub lsfiles {
    my ($dir, $files) = @_;
    my $all = $files =~ /^all$/i;
    my %hash;
    if (not $all) {
        for my $file (split ',', $files) {
            $hash{$file} = 1;
        }
    }
    my @list;
    opendir DIR, $dir or die "Could not open '$dir': $!";
    while (my $entry = readdir DIR) {
        next if (not -f "$dir/$entry");
        if ($all) {
            push @list, $entry;
        } elsif (exists $hash{$entry}) {
            push @list, $entry;
            delete $hash{$entry};
        }
    }
    closedir DIR;
    if (keys %hash) {
        die "Could not find [ " . join (', ', sort keys %hash) . " ]";
    }
    return @list;
}

sub empty {
    shift =~ /^\s*$/ and return 1;
}

sub comment {
    shift =~ /^\s*#/ and return 1;
}

sub trim {
    for (@_) {
        s/^\s+|\s+$//g;
    }
    return @_;
}

sub escape {
    for (@_) {
        s/\\n/\n/g;
        s/\\ / /g;
        s/\\\\/\\/g;
    }
    return @_;
}



sub hashdump {
    my $hash = shift;
    for my $key (keys %$hash) {
        my $val = $hash->{$key};
        if (ref $val eq 'ARRAY') {
            print "'$key' =\n";
            for my $i (@$val) {
                print "\t'$i'\n";
            }
        } else {
            print "'$key' = '$val'\n";
        }
    }
    print "\n\n";
}

1;
