#! perl

# Copyright 2019 Brian Gomes Bascoy
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

use strict;
use warnings;
use utf8;
use List::Util qw(reduce max);

my %resource = (
	foreground => 10,
	background => 11,
	cursorColor2 => 12,
	highlightColor => 17,
	highlightTextColor => 19,
	colorIT => 704,
	colorBD => 706,
	colorUL => 707,
	borderColor => 708
);
$resource{"color$_"} = "4;$_" foreach 0 .. 15;

sub on_start {
	my ($self) = @_;

	foreach my $r (keys %resource) {
		my $Pt = $self->x_resource($r);
		$self->{default_theme} .= OSC($resource{$r}, $Pt) if $Pt;
	}

	$self->grab_button (3, urxvt::ControlMask);
}

sub on_button_press {
	my ($self, $event) = @_;

	if ($event->{button} == 3 && $event->{state} & urxvt::ControlMask) {
		my $popup = $self->popup ($event)
			or return 1;

		my %themes = get_themes();
		{
			my $padding = ' 'x(((reduce {max($a, length($b)+2)} 8, keys %themes)-6)/2);
			$popup->add_title ($padding . 'Themes' . $padding);
		}
		$popup->add_button ('Default', sub{ $self->cmd_parse ($self->{default_theme}) });
		$popup->add_separator ('═');

		foreach my $t (sort keys %themes) {
			$popup->add_button ($t, sub{ $self->cmd_parse ($themes{$t}) });
		}

		$popup->show;

		return 1;
	}
}

sub get_themes {
	my %themes;

	foreach (`xrdb -query`) {
		if (/^URxvt\.theme\.([a-zA-Z0-9_-]+)\.(\w+):\s*(#[0-9a-fA-F]{6})$/) {
			if (exists $resource{$2}) {
				$themes{$1} .= OSC($resource{$2}, $3);
			} else {
 				warn "Unrecognized resource \"$2\"\n"; 
 			}
		}
	}

	return %themes;
}

sub OSC {
	my ($Ps, $Pt) = @_;
	return "\033]$Ps;$Pt\007";
}

# vim:ft=perl:fenc=utf-8
