# Copyright 2002-2021 by Marco d'Itri <md@linux.it>
# vim: set tabstop=4
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Interesting things that you can dump:
# /dump Irssi::channels()
# /dump Irssi::active_win()
#
# Data::Printer has a much nicer output but should be passed a scalar:
# /dump \%ENV
# /dump [Irssi::channels()]
# /dump my $x=Irssi::active_win(); $x->{active_server}
# /dump my $x=Irssi::active_win(); my @l=keys %$x; \@l

use v5.14;
use utf8;
use warnings;
use strict;

use Irssi;
# choose one here:
#use Data::Dumper;
use Data::Printer;

use vars qw($VERSION %IRSSI);

$VERSION = '20210524';
%IRSSI = (
	authors		=> 'Marco d\'Itri',
	contact		=> 'md@linux.it',
	name		=> 'dump',
	description	=> 'dump perl variables in irssi',
	license		=> 'GPLv2+',
	url			=> 'https://www.linux.it/~md/irssi/',
);

Irssi::command_bind('dump' => \&cmd_dump);

sub cmd_dump {
	my ($command, $server, $channel) = @_;

	my @lines =
		map { split(/\n/, $_) }
		map { s/%/%%/g; $_ }
		dump_var($command);
	Irssi::print("$_", MSGLEVEL_CLIENTCRAP) foreach @lines;
	return;
}

sub dump_var {
	if (defined $Data::Printer::VERSION) {
		goto &dump_var_data_printer;
	} elsif (defined $Data::Dumper::VERSION) {
		goto &dump_var_data_dumper;
	}
	die "Either Data::Dumper or Data::Printer must be loaded";
}

sub dump_var_data_dumper {
	my ($v) = @_;

	my $dump = eval "Data::Dumper->new([$v], ['*$v'])";
	if ($@) {
		$@ =~ s/ at \(eval \d+\) line .+\n//;
		Irssi::print("Cannot dump $v:\n$@");
		return;
	}
	$dump->Quotekeys(0);
	$dump->Indent(1);
	return $dump->Dump;
}

sub dump_var_data_printer {
	my ($v) = @_;

	my $dump = eval "$v";
	if ($@) {
		$@ =~ s/ at \(eval \d+\) line .+\n//;
		Irssi::print("Cannot eval $v:\n$@");
		return;
	}
	Irssi::print("====================1");
	return np($dump,
		output => 'stdout',
		colored => 1,
		show_dualvar => 'off',
		print_escapes => 1,
		caller_info => 0,
		filters => [qw(ContentType DateTime DB Digest Web)],
	);
}

