# -*- cperl -*-
package RssC::Formatter;
use strict;
use warnings;
use CGI;
use XML::RSS;
use Time::Zone;

sub new {
    my ($class, $uri, $lastmod, $title) = @_;
    my $this = bless {} => $class;

    $this->{uri} = $uri;
    $this->{lastmod} = $lastmod;
    $this->{title} = $title;

    $this;
}

sub format {
    my $this = shift;
    my $rss = XML::RSS->new(version => '1.0');

    my ($sec, $min, $hour, $day, $mon, $year) = localtime($this->{lastmod});
    $mon++;
    $year += 1900;

    my $tz_hour = tz_local_offset() / 60 / 60;
    my $tz_min = tz_local_offset() / 60 - $tz_hour * 60;

    my $w3c_lastmod = sprintf(
	'%04d-%02d-%02dT%02d:%02d:%02d+%02d:%02d',
	$year, $mon, $day, $hour, $min, $sec, $tz_hour, $tz_min);

    $rss->channel(
	title => $this->{title} || $this->{uri}->as_string,
	link  => $this->{uri}->as_string,
	description => 'Generated by RssC',

	dc => {
	    date    => $w3c_lastmod,
	},
       );

    $rss->add_item(
	title => sprintf(
	    '[RssC] %02d-%02d-%02d %02d:%02d:%02d +%02d:%02d',
	    $year, $mon, $day, $hour, $min, $sec, $tz_hour, $tz_min),
	link  => $this->{uri}->as_string,
	dc    => {
	    date => $w3c_lastmod,
	},
       );

    $rss->as_string;
}

1;
