#/*
# *  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: Thread.pm 164 2007-02-02 14:52:06Z hikarin $
#

package Img0ch::Filter::Thread;

use strict;

sub write_ok {
    my ( $iClass, $args, $iBBS ) = @_;
    my $ip    = $args->{ip};
    my $max   = $args->{max};
    my $id    = $iBBS->get_id();
    my @ip    = unpack 'C4', $ip;
    my $group = ( ( ( $ip[0] % 4 ) * 256 ) + $ip[1] );

    my $iKernel    = $iBBS->get_kernel();
    my $bbs        = $iBBS->get_name() || 'test';
    my $repos_path = $iBBS->get_repos_path('log');
    my $iRepos     = $iKernel->get_repos($repos_path);
    my $max_count  = $iRepos->get_int("I:F:T.${bbs}.max");
    my $min_count  = $iRepos->get_int("I:F:T.${bbs}.min");

    $max_count == $min_count
        and $iRepos->set( "I:F:T.${bbs}.min.id", $group );
    if ( ( $max_count - $min_count ) >= $max ) {
        $iRepos->set( "I:F:T.${bbs}.min", ++$min_count );
        my $remove_group = $iRepos->remove("I:F:T.${bbs}.min.id");
        $iRepos->remove("I:F:T.${bbs}.${remove_group}.ip");
        $iRepos->remove("I:F:T.${bbs}.${remove_group}.time");
        $iRepos->set( "I:F:T.${bbs}.min.id", $group );
    }

    if ( $iRepos->get("I:F:T.${bbs}.${group}.time") ) {
        $args->{error} = 'TOO_MANY_THREADS';
        $iRepos->save();
        return 0;
    }
    else {
        $iRepos->set( "I:F:T.${bbs}.max",           ++$max_count );
        $iRepos->set( "I:F:T.${bbs}.${group}.ip",   join( '.', @ip ) );
        $iRepos->set( "I:F:T.${bbs}.${group}.time", $args->{stamp} );
        $iRepos->save();
        return 1;
    }
}

1;
__END__
