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

# PODNAME: facebook
# ABSTRACT: Bridge facebook events to exobrain

use Exobrain::Bus;
use Exobrain::Message;
use Exobrain::Config;
use JSON::Any;
use Date::Manip::Date;
use Data::Dumper;
use Try::Tiny;

use Facebook::Graph;

use constant DEBUG => 1;

my $POLL_INTERVAL = 60; 
my $last_poll = time() - 3600;

my $bus = Exobrain::Bus->new( type => 'PUB' );

my $config = Exobrain::Config->new;

my $fb = Facebook::Graph->new(
    app_id => $config->{Facebook}{app_id},
    secret => $config->{Facebook}{secret},
);

# For easy access_token generation, set your application to be type
# 'desktop' on developers.facebook.com, and then request the token
# using the API explorer. It should last for months.

$fb->access_token($config->{Facebook}{access_token});

while (1) {
    my $new_polltime = time();

    say "Last poll - $last_poll";

    my $stories;

    try {
        $stories = $fb->query->from('my_news')->select_fields(qw(
            description link name caption id from created_time message
        ))->where_since($last_poll)->request->as_hashref;
    }
    catch {
        warn "$0: $_\n";
        sleep($POLL_INTERVAL);
        next;
    };

    $last_poll = $new_polltime;

    foreach my $story (@{ $stories->{data} }) {
        $bus->send_msg(
            namespace => 'SOCIAL',
            timestamp => $last_poll,    # XXX - Wrong. Get from msg
            source    => 'FACEBOOK',
            data      => {
                user_display => $story->{from}{name},
                user_id      => $story->{from}{id},
            },
            summary   => "$story->{from}{name}: " . ( $story->{message} || "$story->{name} ($story->{caption})" ),
            raw       => $story,
        );
        
        say Dumper $story;
    }

    sleep($POLL_INTERVAL);
}

=pod

=head1 NAME

facebook - Bridge facebook events to exobrain

=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

__END__

my $quote = q{
Humans are not designed to be improved, either by outside neuroscientists, or by recursive self-improvement internally. Natural selection did not build the human brain to be humanly hackable. All complex machinery in the brain has adapted to operate within narrow parameters of brain design. Suppose you can make the human smarter, let alone superintelligent; does the human remain sane?

— Eliezer Yudkowski, Artificial Intelligence as a Positive and Negative Factor in Global Risk
};

$fb->add_post
   ->set_message($quote)
   ->set_privacy('EVERYONE', {})        # Validates but does not work
   ->publish
;

