package Plagger::Plugin::CustomFeed::LWWS;
use strict;
use base qw( Plagger::Plugin );

use WebService::Livedoor::Weather;
use Encode;
use URI;

sub register {
    my($self, $context) = @_;
    $context->register_hook(
	$self,
	'subscription.load' => \&load,
	'aggregator.aggregate.lwws' => \&aggregate
    );
}

sub load {
    my($self, $context) = @_;
    my $feed = Plagger::Feed->new;
    $feed->type('lwws');
    $context->subscription->add($feed);
}

sub aggregate {
    my($self, $context, $args) = @_;
    $context->error('config city is missing') unless $self->conf->{city};

    my $cities = $self->conf->{city};
    $cities = [$cities] unless ref $cities;
    my $days = $self->conf->{day} || ['today'];
    $days = [$days] unless ref $days;

    my $lwws = WebService::Livedoor::Weather->new;
    my $feed = Plagger::Feed->new;
    $feed->type('lwws');
    $feed->link('http://weather.livedoor.com/');
    my @locations;

    for my $day (@$days) {
	for my $city (@$cities) {

	    my $ret;
	    eval{
		$ret = $lwws->get($city,$day);
	    };
	    $context->log(error=>'Retieving weather information faild:'.$@),next if $@;

	    push(@locations,$ret->{location}{city});

	    $ret->{forecastdate} =  Plagger::Date->parse('Mail',$ret->{forecastdate})->set_locale('ja');
	    $ret->{publictime} = Plagger::Date->parse('Mail', $ret->{publictime})->set_locale('ja');

	    my $entry = Plagger::Entry->new;
	    $entry->author($ret->{author});
	    $entry->date($ret->{publictime});
	    $entry->title(
		sprintf(decode_utf8("[%s日(%s)の天気] %s - %s - 最高気温%s℃ - %s月%s日(%s)"),
	        $ret->{forecastdate}->day,
		$ret->{forecastdate}->day_abbr,
		$ret->{location}{city},
		$ret->{telop},
		$ret->{t_max} || "-",
		$ret->{forecastdate}->month,
		$ret->{forecastdate}->day,
		$ret->{forecastdate}->day_abbr
	    ));
	    my $uri = URI->new($ret->{link});
	    $uri->query_form(r=>'rss'.$ret->{forecastdate}->ymd(''));
	    $entry->link($uri->as_string);

	    my $tt = $context->template();
	    $tt->process("lwwp.tt", {
		w => $ret,
	    }, \my $body) or $context->error($tt->error);
	    $entry->body($body);

	    $feed->add_entry($entry);

	}
    }

    my %chk;
    my $title = join decode_utf8("・"), grep{!$chk{$_}++} @locations;
    $feed->title($title.decode_utf8("の天気 - Livedoor Weather Hacks"));
    $context->update->add($feed);
}

1;

__END__
config example
  - module: CustomFeed::LWWS
    config:
      city: 79
      day:
        - today
        - tomorrow



