# This file is part of "KarmaLab.net Perl Library".
#    Copyright 2005, Yoran Brault
#    eMail: yoran.brault@bad_karma-lab.net (remove "bad_" before sending)
#    Site : http://artisan.karma-lab.net
#
# "KarmaLab.net Perl Library" is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# "KarmaLab.net Perl Library" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with "KarmaLab.net Perl Library"; if not, write to the Free
# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA, or see the FSF site: http://www.fsf.org.

package Logging::Formaters::ColoredLogFormater;

use strict;
use warnings;


use base "Logging::Formaters::AbstractLogFormater";
use Logging::Formaters::AbstractLogFormater;

use Term::ANSIColor;
use Term::ANSIColor qw(:constants);
use Time::localtime;
use Logging::Level;

sub new {
    my $self  = shift->SUPER::new;
    return $self;
}

sub useColors {
    my $self = shift;
    if (shift) {
        $ENV{'ANSI_COLORS_DISABLED'} = undef;
    }
    else {
        $ENV{'ANSI_COLORS_DISABLED'} = 1;
    }
}

sub _trim {
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}



sub format () {
    my $self   = shift;
    my $record = shift;

    my $data  = "";
    my $color = WHITE;
    if ( $record->level == LEVEL_DEBUG ) {
        $color = CYAN;
    }
    elsif ( $record->level == LEVEL_TRACE ) {
        $color = WHITE;
    }
    elsif ( $record->level == LEVEL_WARNING ) {
        $color = YELLOW;
    }
    elsif ( $record->level == LEVEL_INFO ) {
        $color = BOLD.WHITE;
    }
    elsif ( $record->level == LEVEL_SEVERE ) {
        $color = RED;
    }
    $data .= "$color";
    my @lines = split( /\n/,  $record->message  );
    my $iCount = 0;
    for (@lines) {
        if ( ( $self->options & INSERT_TIMESTAMPS ) != 0 or ( $self->options & INSERT_PIDS ) != 0 ) {
            if ( $iCount == 0 ) {
                if ( ( $self->options & INSERT_TIMESTAMPS ) != 0 ) {
                    $data .= sprintf( "%s ", ctime() );
                }
                if ( ( $self->options & INSERT_PIDS ) != 0 ) {
                    $data .= sprintf( "[%6s] ", getppid() );
                }
            }
            else {
                $data .= "                                  ";
            }
            $data .= "- ";
        }
        $data .= "$_";
        if (!$record->fragment && $record->level!=LEVEL_PROGRESS) {
            $data .= "\n";
        }
        $iCount++;
    }
    return $data;
}
1;
