# Copyrights 2007-2015 by [Mark Overmeer].
#  For other contributors see ChangeLog.
# See the manual pages for details on the licensing terms.
# Pod stripped from pm file by OODoc 2.01.
package Dancer2::Logger::LogReport;
use vars '$VERSION';
$VERSION = '1.07';

# ABSTRACT: Dancer2 logger engine for Log::Report

use strict;
use warnings;

use Moo;
use Dancer2::Core::Types;
use Scalar::Util qw/blessed/;
use Log::Report  'logreport', syntax => 'REPORT', mode => 'DEBUG';

our $AUTHORITY = 'cpan:MARKOV';

# all dispatchers shall be created exactly once (unique name)
my %disp_objs;

my %level_dancer2lr =
  ( core  => 'TRACE'
  , debug => 'TRACE'
  );

with 'Dancer2::Core::Role::Logger';

# Set by calling function
has dispatchers =>
  ( is    => 'ro'
  , isa   => Maybe[HashRef]
  , lazy  => 1
  );

sub BUILD ()
{   my $self     = shift;
    my $configs  = $self->dispatchers || {default => undef};
    $self->{use} = [keys %$config];

    foreach my $name (keys %$configs)
    {   my $config = $configs->{$name} || {};
        if(keys %$config)
        {   # cannot use log() output yet!  recursion!
            ! $disp_objs{$name}
                or die "attempt to reconfigure dispatcher $name";

            my $type = delete $config->{type}
                or die "dispatcher configuration $name without type";

            $disp_objs{$name} = dispatcher $type, $name, %$config;
        }
    }
}


sub log($$$)
{   my ($self, $level, $params) = @_;

    # all dancer levels are the same as L::R levels, except:
    my $msg;
    if(blessed $params && $params->isa('Log::Report::Message'))
    {   $msg = $params;
    }
    else
    {   $msg = $self->format_message($level => $params);
        $msg =~ s/\n+$//;
    }

    # the levels are nearly the same.
    my $reason = $level_dancer2lr{$level} // uc $level;

    report {is_fatal => 0}, $reason => $msg, to => $self->{use};

    undef;
}
 
1;
