#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
use utf8::all;
use autodie qw(:all);

use Exobrain;
use Exobrain::Cache;
use Date::Manip::Date;
use Try::Tiny;

use Net::Twitter;

# PODNAME: twitter
# ABSTRACT: Bridge twitter events to the exobrain bus

use constant DEBUG => 1;
use constant LAST_CHECK => 'last_check';

my $exobrain = Exobrain->new;

my $config = $exobrain->config->{Twitter};

my $twitter = Net::Twitter->new(
    traits   => [qw(API::RESTv1_1)],
    consumer_key        => $config->{consumer_key},
    consumer_secret     => $config->{consumer_secret},
    access_token        => $config->{access_token},
    access_token_secret => $config->{access_token_secret},
    ssl                 => 1,
);

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

# Fetch our last ID from the cache, or otherwise just pick
# the last mention we've seen.

my $last_id = $cache->compute(LAST_CHECK, undef,
    sub { $twitter->mentions({count => 1})->[0]{id} }
);

my $last_error = "";

while (1) {

    sleep(90);

    my $statuses;

    try { 
        $statuses = $twitter->mentions({since_id => $last_id});
    }
    catch {
        # TODO: Signal to our owner that something is wrong if
        # we see too many errors in a row.
        warn $_;
        next;
    };

    for my $status ( @$statuses ) {
        my $text = $status->{text};
        my @tags;

        # TODO: Move all this into the Measurement::Tweet class,
        # so it can auto-inflate from a single tweet

        while ($text =~ m{\#(?<tag>\w+)}g) {
            push @tags, $+{tag};
        }

        my $epoch_time = do {
            my $dmd = Date::Manip::Date->new;
            my $timestamp = $status->{created_at};
            $dmd->parse($timestamp) and die "Can't parse $timestamp";
            $dmd->printf("%s");
        };

        print "[$status->{id}] $epoch_time <$status->{user}{screen_name}> $status->{text} (Tags: @tags)\n" if DEBUG;

        # TODO: Parse or figure out who this is to, for the 'to' attribute.

        $exobrain->measure('Tweet',
            timestamp => $epoch_time,
            from      => $status->{user}{screen_name},
            tags      => \@tags,
            to_me     => 1,     # Because we're only looking at replies
            text      => $status->{text},
            raw       => $status,
        )->send_msg;

        if ($status->{id} > $last_id) {
            $last_id = $status->{id};
            $cache->set(LAST_CHECK, $last_id);
        }
    }
}

__END__

=pod

=head1 NAME

twitter - Bridge twitter events to the exobrain bus

=head1 VERSION

version 0.06

=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
