#/*
# *  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: Pool.pm 1300 2007-10-06 13:25:23Z hikarin $
#

package Zeromin2::Translate::Img0ch::v2::Pool;

use strict;
use File::Spec qw();
use Img0ch::Pool::Thread qw();
use Img0ch::Pool::Subject qw();
use Zeromin::BBS qw();
use Zeromin::Thread qw();

sub work {
    my ( $zClass, $iKernel ) = @_;

    my $zBBS = Zeromin::BBS->new( $iKernel, { id => 0 } );
    my $bbs_all = $zBBS->all();
    foreach my $bbs (@$bbs_all) {
        my $iBBS = Img0ch::BBS->new( $iKernel, { id => $bbs->{id} } );
        _aggregate( $iKernel, $iBBS );
    }

    return { code => 0, pool => 1 };
}

sub _aggregate {
    my ( $iKernel, $iBBS ) = @_;
    my $base = $iBBS->path('pool');
    -d $base or return;

    opendir my $fh, $base or $iKernel->throw_io_exception($base);
    my @dirs = readdir $fh;
    closedir $fh or $iKernel->throw_io_exception($base);

    my $iPSubject = Img0ch::Pool::Subject->new($iBBS);
    my $iPThread  = Img0ch::Pool::Thread->new($iBBS);
    my $iThread   = Img0ch::Thread->new($iBBS);

    for my $file ( File::Spec->no_upwards(@dirs) ) {
        $file =~ m{\A(\d{9,10})\.cgi\z}xms or next;

        my $key = $1;
        $iThread->set_key($key);
        $iPThread->set_key($key);
        $iThread->load( File::Spec->catfile( $base, $file ) );

        my $count   = $iThread->count();
        my $subject = $iThread->get_subject();
        $iPThread->set( [ @{ $iThread->get(1) }, $subject ], 1 );
        for ( my $i = 2; $i <= $count; $i++ ) {
            $iPThread->set( $iThread->get($i), $i );
        }

        $iPThread->save();
        $iPSubject->set( $key, $count, $subject );
    }
    $iPSubject->save();

    return;
}

1;
__END__
