#/*
# *  Copyright 2007 hkrn <hikarin@users.sourceforge.jp>
# *
# *  Licensed under the Apache License, Version 2.0 (the "License");
# *  you may not use this file except in compliance with the License.
# *  You may obtain a copy of the License at
# *
# *      http://www.apache.org/licenses/LICENSE-2.0
# *
# *  Unless required by applicable law or agreed to in writing, software
# *  distributed under the License is distributed on an "AS IS" BASIS,
# *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# *  See the License for the specific language governing permissions and
# *  limitations under the License.
# */
#
# $Id: RSS.pm 419 2007-03-24 13:25:11Z hikarin $
#

package Img0ch::Plugin::BBS::RSS;

use strict;
use Unicode::Japanese qw();
use XML::RSSLite qw();

sub generate_ver_10 {
    my ($iApp) = @_;
    my $ref    = shift;
    my $self   = {};

    my @d = localtime( time() );
    $d[5] += 1900;
    $d[4] += 1;
    my $format = '%04d-%02d-%02dT%02d:%02d:%02d+09:00';
    my $date = sprintf $format, $d[5], $d[4], $d[3], $d[2], $d[1], $d[0];

    my $iBBS     = $iApp->bbs();
    my $iKernel  = $iApp->kernel();
    my $iConfig  = $iKernel->get_config();
    my $iSetting = $iApp->setting();
    my $bbs      = $iBBS->get_name();
    my $encoding = $iKernel->get_encoding(1);
    my $unijp    = Unicode::Japanese->new();
    my $url      = $iBBS->url();
    my $path     = $iBBS->path('index.rdf');
    my $title = $unijp->set( $iSetting->get('BBS_TITLE'), $encoding )->get();
    my $subt
        = $unijp->set( $iSetting->get('BBS_SUBTITLE'), $encoding )->get();
    my %rss = ();

    if ( open( my $fh, '<', $path ) ) {
        local $/ = undef;
        my $content = <$fh>;
        close $fh or $iKernel->throw_io_exception($path);
        XML::RSSLite::_parseRDF( \%rss, \$content );
        XML::RSSLite::postprocess( \%rss );
    }
    else {
        $rss{'items'} = [];
    }

    my $name = $unijp->set(
        Img0ch::Kernel::escape_html_entities( $iApp->get_name() ), $encoding )
        ->get();    # dc:creator
    my $comment = $unijp->set(
        Img0ch::Kernel::escape_html_entities( $iApp->get_comment() ),
        $encoding )->get();    # description
    my $iRequest = $iApp->request();
    my $channel = {
        'title'          => $title,        # channel/title
        'description'    => $subt,         # channel/description
        'link'           => $url,          # channel/url
        'dc:creator'     => $iRequest->signature(),
        'dc:language'    => 'ja',
        'dc:date'        => $date,
        'generatorAgent' => __PACKAGE__,
    };

    my $iThread = $iApp->thread();
    my $key     = $iThread->get_key();
    my $count   = $iThread->count() + 1;
    my $cgipath = $iRequest->get_app_uri();
    my $resource = join '/', $cgipath, 'read.cgi', $bbs, $key, $count;
    $rss{'channel'} ||= { 'items' =>
            { 'rdf:Seq' => { 'rdf:li' => [ { 'rdf:resource' => '' }, ], }, },
    };
    while ( my ( $key, $value ) = each %$channel ) {
        $rss{'channel'}->{$key} = $value;
    }

    $rss{'rdf:resource'} = [];
    push @{ $rss{'rdf:resource'} }, $resource;
    my $rdf = $rss{'channel'}->{'items'}->{'rdf:Seq'}->{'rdf:li'};
    ( ( ref $rdf || '' ) eq 'ARRAY' ) or $rdf = [$rdf];
    for my $one (@$rdf) {
        my ( undef, $value ) = each %$one;
        $value or next;
        push @{ $rss{'rdf:resource'} }, $value;
    }

    my $subject = $unijp->set( $iThread->get_subject(), $encoding )->get();
    unshift @{ $rss{'items'} },
        {
        'title'       => $subject,
        'link'        => $resource,
        'description' => $comment,
        'dc:subject'  => $subject,
        'dc:creator'  => $name,
        'dc:date'     => $date,
        'rdf:about'   => $resource,
        };
    my $max = 10;

    #    my $max = __PACKAGE__->config($bbs)->{max} || 10;
    if ( scalar( @{ $rss{'items'} } ) > $max ) {
        pop @{ $rss{'items'} };
        pop @{ $rss{'rdf:resource'} };
    }
    _save( $iKernel, \%rss, $path );
    return 1;
}

sub _save {
    my ( $iKernel, $rss, $path ) = @_;
    local ( $!, *FH );

    open *FH, ">${path}" or $iKernel->throw_io_exception($path);  ## no critic
    print {*FH} <<"RSS10_FEED" or $iKernel->throw_io_exception($path);
<?xml version="1.0" encoding="utf-8"?>

<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:admin="http://webns.net/mvcb/"
xmlns:cc="http://web.resource.org/cc/"
xmlns="http://purl.org/rss/1.0/">

<channel>
<title>$rss->{'channel'}->{'title'}</title>
<link>$rss->{'channel'}->{'link'}</link>
<description>$rss->{'channel'}->{'description'}</description>
<dc:language>$rss->{'channel'}->{'dc:language'}</dc:language>
<dc:creator>$rss->{'channel'}->{'dc:creator'}</dc:creator>
<dc:date>$rss->{'channel'}->{'dc:date'}</dc:date>
<admin:generatorAgent rdf:resource="$rss->{'channel'}->{'generatorAgent'}" />
<items>
<rdf:Seq>
@{[
 map{
  qq{<rdf:li rdf:resource="$_" />}
 } @{$rss->{'rdf:resource'}}
]}
</rdf:Seq>
</items>
</channel>

@{[
 map{
  qq{
<item rdf:about="$_->{'rdf:about'}">
<title>$_->{'title'}</title>
<link>$_->{'link'}</link>
<description>$_->{'description'}</description>
<dc:subject>$_->{'dc:subject'}</dc:subject>
<dc:creator>$_->{'dc:creator'}</dc:creator>
<dc:date>$_->{'dc:date'}</dc:date>
</item>
  }
 } @{$rss->{'items'}}
]}

</rdf:RDF>
RSS10_FEED
    close *FH or $iKernel->throw_io_exception($path);
}

1;
