package WarnColor;

use warnings;
use strict;

use POSIX qw(strftime);

sub BEGIN {

	sub port2color {
		my $port = shift;
		return "\e[1m0\e[0m" if $port == 0;

		my $c = ( $port % 6 ) + 31;
		return "\e[${c}m$port\e[0m";
	}

	sub __log {
		my $log = $ENV{SLICE} ? "$ENV{SLICE}/log/" : '/tmp/';

		my ( $ss,$mm,$hh, $d,$m,$yyyy ) = localtime(time());
		$yyyy += 1900;
		$m    += 1;

		$log .= sprintf("%04d-%02d-%02d.", $yyyy, $m, $d );

		$log .= $ENV{NAME}  ? $ENV{NAME} : $1 if $0 =~ m{([^/]+)$};

		my $line = join(' ', @_);
		if ( $line =~ s{^(?:\e\[\d+m)*(\d\d\d\d)\W(\d\d)\W(\d\d) (\d\d:\d\d:\d\d)}{$1-$2-$3 $4} ) {
			# have timestamp allready
		} else {
			my $time = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $yyyy,$m,$d, $hh,$mm,$ss);
			$line = "$time $line";
		}

		$line =~ s/[\r\n]+$/\n/;

		print STDERR "creating $log\n" unless -e $log;

		if ( open(my $fh, '>>', $log) ) {
			print $fh $line;
			close $fh;
		} else {
			print STDERR $line;
		}
	}

if ( -t STDOUT ) { # colorize only if run from terminal !

	$SIG{__WARN__} = sub {
		return unless @_;
		my $msg = join('', @_);
		if ( $msg =~ s{ line (\d+)\.}{ +$1} ) {
			$msg =~ s{^(.+)( at .+)}{\e[31m$1\e[0m$2} if $msg !~ m{^#};
		}
		$msg =~ s{\[(\d+)\]}{ '[' . port2color($1) . ']' }eg;
		$msg =~ s{(\||=>)}{\e[34m$1\e[0m}g; # blue
		$msg =~ s{(["\{\}\#])}{\e[33m$1\e[0m}g; # yellow
		__log $msg unless $msg =~ m{^#} && ! $ENV{DEBUG};
		return 1;
	};

} else {

	$SIG{__WARN__} = sub {
		__log @_;
	};

	$SIG{__DIE__} = sub {
		if($^S) {
			# We're in an eval {} and don't want log
			# this message but catch it later
			return;
		}
		__log 'DIE', @_;
		die @_;
	};

}

} # BEGIN

1;
