#!/usr/bin/perl
use warnings;
use strict;

my $trend = {
	hist_spec => {
		'fade/LDR' => '300x1',
		'__default' => '100x1',
	}
};

sub DESTROY {
	warn "DESTROY";
	system "killall mosquitto_sub trend";
}
system "killall mosquitto_sub trend";
system "i3-msg layout splitv";
#system "i3-msg border none";

my $border = 2;

my $topic = 'fade/#';
$topic = $ARGV[0] if $ARGV[0];

open(my $in, '-|', "mosquitto_sub -h rpi2 -t '$topic' -v");
while(<$in>) {
	s/\s+$//sg;

	my ($t,$v) = split(/\s/,$_,2);
	print STDERR "$t=$v ";

	if ( ! exists $trend->{$t} && $v =~ m/^\d+/ ) {
		my $hist = $trend->{hist_spec}->{$t} || $trend->{hist_spec}->{__default};
		my $label = $t;
		$label =~ s/^.+\///;
		open($trend->{$t}, '|-', "trend -L $label -v - $hist");
		$border = 2;
	}

	if ( $trend->{$t} ) {
		select $trend->{$t};
		$| = 1;
		print "$v\n";
	} else {
		warn "CLOSED $!\n";
	}

	system "i3-msg border 1pixel" if $border-- > 0;
}

