package Dojo::Support;
use strict;
use warnings;
use Exporter 'import';
our @EXPORT = qw/ log dmph merge_hash load_module get_names /;
use Mojo::Base 'Mojolicious';

use File::Basename;
use Mojo::File 'path';
use Path::Class;
use Encode qw{ decode_utf8 };
use Hash::Merge;
use Dojo::Conf;
use Mojo::Log;

sub log{
  my $log = Mojo::Log->new;
  $log->debug("============   ".shift."   ===========");
}
sub get_names{
  my $dir = shift;
  my @file_name;
  opendir(DIR, $dir) or die "error opening dir: $dir \n$!";
  while (my $file = readdir(DIR)) {
    next unless ( $file =~m/^[\w\d]/);
    next unless (-f "$dir/$file");
    push(@file_name,$file);
  }
  closedir(DIR);
  return sort @file_name;
};

sub merge_hash{
  #my ($v,$w)=@_;
  my $h={};
  my $merger = Hash::Merge->new('LEFT_PRECEDENT');
  foreach (@_){
   $h= $merger->merge($h,$_);
 }
 return $h;
}

sub load_module{
  my $dir=shift;
  my $lpath= Dojo::Conf::MOD."/$dir";
  my $h; 
  $h->{layout} = "default";
  my $q; 
  my @s= get_names($lpath);
  foreach (@s) {
    push(@{$h->{$1}}, "/$dir/$_") if /.*\.(css|js)$/;
    push(@{$q->{$1}}, "/$dir/$_") if /.*\.(q|json|txt|md)$/;
  }
  return ($h,$q); 
};


sub dmph{
  my $x = shift;
  my $y=" ";
  foreach (sort(keys %$x)) {
   $y= "$y $_ = $x->{$_} \n";
  }   
  return $y; 
}


1;
