#!/usr/bin/perl -w
use 5.010;
use strict;
use warnings;
use autodie;
use POSIX qw(strftime);

# PODNAME: sentbox-reward
# ABSTRACT: Reward users on HabitRPG for sending email.

use Getopt::Std;
use Exobrain;
use Exobrain::Cache;
use Exobrain::Intent::HabitRPG;
use WebService::RTMAgent;
use Data::Dumper;

use constant DEBUG => 1;

# TODO: Upgrade this to use watch_loops

my $exobrain = Exobrain->new;

my $bus       = $exobrain->sub;
my $responder = $exobrain->pub;
my $config    = $exobrain->config;

my $cache  = Exobrain::Cache->new(namespace => $0);

my $task  = $config->{'Sendbox-Reward'}{task} or die "No HabitRPG task";
my $send_tweet = $config->{'Sendbox-Reward'}{tweet} || 0;

warn "Starting $0\n" if DEBUG;

while (my $raw_event = $bus->get) {
    if (my $tags = $raw_event->namespace eq 'EMAIL') {

        warn "Examining email event\n" if DEBUG;

        my $event = $raw_event->to_class('Measurement::Mailbox');

        my $mbox = $event->mailbox or next;

        # Only look at sent mail.
        next unless $mbox =~ /sent/i;

        my $key = [ $event->server, $mbox ];
        my $count = $event->count;

        my $old_count = $cache->get( $key ) || 0;

        warn "Handling @$key at $count (from $old_count) msgs\n" if DEBUG;

        if ($count > $old_count) {
            # Sweet! They sent email
            $cache->set( $key, $count );

            Exobrain::Intent::HabitRPG->new(
                task => $task,
                direction => 'up',
                public => $send_tweet,
            )->send_msg( $responder->_socket );
        }
    }
}

__END__

=pod

=head1 NAME

sentbox-reward - Reward users on HabitRPG for sending email.

=head1 VERSION

version 1.00

=head1 AUTHOR

Paul Fenwick <pjf@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2014 by Paul Fenwick.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
