use strict;
package MiscUtils;

require Exporter;
require Carp;

our @ISA = qw(Exporter);
our @EXPORT = qw(rindent indent mkdirs swap_dirs filter_text array_to_hash debug);
our $VERSION = v1.0.0;

sub rindent {
	my $ident = shift();
	my $tmp = '';

	while ($ident--) {
		$tmp .= "\t";
	}

	return $tmp;
}

sub indent {
	my ($indent, $fh) = @_;

	if ($fh) { print $fh rindent ($indent); }
	else { print rindent ($indent); }
}

sub mkdirs {
  my $full_path = $_[0];
  return if (-d $full_path);
  $full_path =~ s-^((?:/)?.+)/.+?$-$1/-;
  my @all_dirs = split(/\//, $full_path);
  my ($dir, $tmp_dir) = ();
  foreach $dir (@all_dirs) {
    $tmp_dir .= "$dir/";
    if (!-e $tmp_dir) {
       if (!mkdir($tmp_dir)) {
        return 0;
      }
    }
  }

  return 1;
}

sub swap_dirs {
	my ($path, $from, $to) = @_;
	$path =~ s/^$from/$to/i;
	return 	($path);
}

sub filter_text {
	my $dirty_text = shift();

	# trim
	$dirty_text =~ s/^ +//;		$dirty_text =~ s/ +$//;

	# "smart" quotes X{
	$dirty_text =~ tr/\x93\x94/"/;	$dirty_text =~ tr/\x92/'/;

	# convert special chars
	$dirty_text =~ s/&/&amp;/g;
	$dirty_text =~ s/</&lt;/g;	$dirty_text =~ s/>/&gt;/g;
	$dirty_text =~ s/"/&quot;/g;	$dirty_text =~ s/'/&#39;/g;

	return $dirty_text;
}

sub debug {
	my ($whatnot, $name, $indent) = @_;

	$name = 'VARIABLE' if (!$name);
	$whatnot = '(empty)' if (!$whatnot);

	if (ref($whatnot) eq 'ARRAY') {
		$indent++;
		for (my $i = 0; $i < scalar(@{ $whatnot }); $i++) {
			debug ($whatnot->[$i], "${name}\[$i\]", $indent);
		}
		$indent--;
	}
	elsif (ref($whatnot) eq 'HASH') {
		$indent++;
		foreach my $item (keys %{ $whatnot }) {
			debug ($whatnot->{$item}, "${name}\{$item\}", $indent);
		}
		$indent--;
	}
	elsif (ref($whatnot) eq 'SCALAR') {
		debug ($$whatnot, $name, $indent);
	}
	elsif (ref($whatnot) eq 'CODE') {
		debug ('a code reference', $name, $indent);
	}
	else {
		print ("debug: ");
		while ($indent--) { print "\t"; }
		print ("$name is $whatnot\n");
	}
}

1;