package LIMS::Local::LogDispatch;

use Config::Auto;
use LIMS::Local::Utils;

use Log::Dispatch;
use Log::Dispatch::File;
use Log::Dispatch::Screen;
use Log::Dispatch::Email::MailSendmail;

use Data::Dumper;

require Exporter;

@EXPORT = qw(
  log_dispatch
);

use strict;

sub log_dispatch {
    my $self = shift;

    if (! $self->stash->{log_dispatch} ) {
        my $path_to_app_root = LIMS::Local::Utils::find_home; # warn "$_: $ENV{$_}\n" for sort keys %ENV;

        # TODO: shouldn't need this, but $self->cfg->{log_dispatch} contains mysterious 'callbacks'
        my $config = Config::Auto::parse($path_to_app_root.'/config/lims_log_dispatch.pl', format => 'perl');
        # warn Dumper $config;

        my $dispatcher = Log::Dispatch->new;

        my $log_dispatch_mods =
            $config->{log_dispatch}->{LOG_DISPATCH_MODULES}; # warn Dumper $log_dispatch_mods;
           # $self->cfg->{log_dispatch}->{LOG_DISPATCH_MODULES};  # module key replace by callback !!

        foreach my $entry (@$log_dispatch_mods) { # warn Dumper $entry;
            my $module = $entry->{module};

            my %args =
                map { $_ => $entry->{$_} }
                    grep { $_ ne 'module' } # already used it for $module
                        keys %$entry; # warn Dumper \%args;

            $dispatcher->add(
                $module->new(%args),
            );
        }

        $self->stash( log_dispatch => $dispatcher ); # warn Dumper $dispatcher;
    }

    return $self->stash->{log_dispatch};
}

1;