# $HeadURL$
# $LastChangedRevision$
# $LastChangedDate$
# $LastChangedBy$

package OpenGuides::SpamPlugin::Akismet;

use strict;
use warnings;

use Net::Akismet;
use Data::Dumper;
use Config::Tiny;
use MIME::Lite;
use Readonly;

Readonly my %NODES_SKIP_CHECK => (
    'Co-Op Walton Street' => 1,
    'Home' => 1,
);

sub notify_admins {
    my ( $class, %args ) = @_;
    print STDERR "Akismet deny:\n" . Dumper( \%args );
    return;
    my $message = MIME::Lite->new(
        From     => $args{email},
        To       => $args{email},
        Subject  => "Attempted spam edit on " . $args{'url'},
        Data     => "Someone just tried to edit " . $args{'url'} . ", and "
                    . "Akismet said no.\n\n"
                    . "Here's a dump of the details:\n"
                    . Dumper( \%args ),
    );
    $message->send;
}

sub looks_like_spam {
    my ( $class, %args ) = @_;
    # http://dev.openguides.org/ticket/253
    # shouldn't have to fish this out ourselves
    # hacking core OpenGuides code is for another day
    my $config = Config::Tiny->read('wiki.conf');
    my $api_key = $config->{'akismet'}->{'spam_detector_akismet_key'};
    my $url = $config->{_}->{'script_url'};
    my $email = $config->{_}->{'contact_email'};

    return 0 if $NODES_SKIP_CHECK{$args{node}};

    my $akismet = Net::Akismet->new(
        KEY => $api_key,
        URL => $url,
    )
        or die "Could not verify API key\n";
    my %check_data = (
        USER_IP => $ENV{'REMOTE_ADDR'},
        COMMENT_USER_AGENT => $ENV{'HTTP_USER_AGENT'},
        COMMENT_CONTENT => $args{content},
        COMMENT_AUTHOR => $args{metadata}->{username},
    );
    my $result = $akismet->check( %check_data );

    if ( $result eq 'true' ) {
        $class->notify_admins( %args, url => $url, email => $email );
        return 1;
    } else {
        return 0;
    }
}

1;
