package Plagger::Plugin::Publish::IRC;
use strict;
use base qw( Plagger::Plugin );

use Encode;

sub register {
    my($self, $context) = @_;
    $context->register_hook(
        $self,
        'publish.add_feed' => \&update,
    );
}

sub update {
    my($self, $context, $args) = @_;

    no warnings 'once';    # i use package variables below
    require POE::Component::IKC::ClientLite;
    my $remote = POE::Component::IKC::ClientLite::create_ikc_client(
        port    => $self->conf->{daemon_port},
        ip      => $self->conf->{daemon_host},
        name    => "Plagger$$",
        timeout => 5,
        )
        or die $POE::Component::IKC::ClientLite::error;

    my $feed = $args->{feed};
    my $subject = $feed->title || '(no-title)';
    my $body = $self->templatize($context, $feed);
    Encode::_utf8_off($body) if Encode::is_utf8($body);
    Encode::from_to($body, 'utf8', 'iso-2022-jp');
    for my $line (split("\n", $body)) {
        $remote->post( 'notify_irc/update', $line );
    }
}

sub templatize {
    my($self, $context, $feed) = @_;
    my $tt = $context->template();
    $tt->process('irc_notify.tt', {
        feed => $feed,
    }, \my $out) or $context->error($tt->error);
    $out;
}

1;
