# 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::Handlers::ConsoleLogHandler;

use strict;
use warnings;
use Logging::Level;
use base 'Logging::Handlers::AbstractLogHandler';
use Term::ANSIColor;
use Term::ANSIColor qw(:constants);
use IO::Handle;
use Term::Size;

sub BEGIN {
    binmode STDOUT, ":utf8";
    binmode STDERR, ":utf8";
    STDOUT->autoflush(1);
    STDERR->autoflush(1);
}

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

my @PROGRESS_PATTERNS = ( "|","/","-","\\");

sub handle () {
    my $self    = shift;
    my $manager = shift;
    my $log     = shift;

    my $message = $manager->formater->format($log);
    if ( $log->level == LEVEL_SEVERE ) {
        print STDERR $message.RESET;
    }
    elsif ( $log->level == LEVEL_PROGRESS ) {
        my ($columns, $rows) = Term::Size::chars *STDOUT{IO};
        $columns-=5;
        if (length($message)>$columns) {
            $message=substr($message, 0,$columns);
        }
        my $indicator="";
        if ($message =~ /STOP/) {
            $message='';
        } else {
            $self->{progress}++;
            my $pos=$self->{progress} % 4;
            $message=WHITE."   [".GREEN.$PROGRESS_PATTERNS[$pos].WHITE."] ".$message;
        }
        print STDOUT  $message="\r\e[K$message".RESET;
        STDOUT->flush;
    }    
    else {
        print STDOUT $message.RESET;
    }
}
1;
