package Message;

use strict;
use vars qw(@ISA @EXPORT $quiet $term_lines $term_cols $use_colour);

use Exporter;

if (-t) {
	($term_lines, $term_cols) = split / /, `stty size`;
} else {
	($term_lines, $term_cols) = (25, 80);
}

my $term = $ENV{TERM};
$use_colour = 1;

@ISA = qw(Exporter);
@EXPORT = qw(quiet comment message error fatal question heading coloured colour colour_out view debug);

$quiet = 1;

sub monochrome {
	$use_colour = '';
}

sub colour {
	my $colour = shift;
	return $use_colour && "\033[1;3${colour}m";
}

sub colour_out {
	return $use_colour && "\033[0m";
}

sub quiet {
	if (@_ == 2) {
		$quiet = $_[1];
	} else {
		return $quiet;
	}
}

sub debug {
	print STDERR "@_\n" if $quiet < 0;
}

sub comment {
	print STDERR "@_\n" unless $quiet > 0;
}

sub message {
	print STDERR "@_\n" unless $quiet > 1;
}

sub error {
	print STDERR colour(1), "@_\n", colour_out();
}

sub fatal {
	print STDERR colour(1), "@_\n\n", colour_out();
	exit 1;
}

sub question {
	local $| = 1;
	print colour(2), "@_", colour(3);
	my $input = <>;
	chomp($input) if defined $input;
	print colour_out();
	return $input;
}

sub heading {
	coloured(7, @_) unless $quiet > 1;
}

sub coloured {
	return if $quiet > 1;
	my $colour = shift;
	local $| = 1;
	print colour($colour), "@_\n", colour_out();
}

# this runs a pager if the file is large...
# BUG: will not work with dodgy filenames (e.g. with spaces in them)
sub view {
	my ($file) = @_;
	(my $wc = `wc -l $file`) =~ tr/0-9//cd;
	if ($wc > $term_lines - 5) {
		system "pager $file";
	} else {
		system "cat $file";
	}
}

1
