#/*
# *  Copyright 2007-2008 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 1645 2008-02-06 15:40:18Z hikarin $
#

package Img0ch::Filter::Thread;

use strict;

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

    my $iKernel = $iBBS->get_kernel();
    my $iRepos  = $iKernel->get_repos( $iKernel->get_repos_path('restrict') );
    my $bbs     = $iBBS->get_name() || 'test';
    my @data    = split "\n", $iRepos->get_binary("I:F:T.${bbs}");

    scalar(@data) > $max and shift @data;
    for my $datum (@data) {
        my ( $ip_group, undef, $ip ) = split "\t", $datum, 3;
        if ( $ip_group == $my_group ) {
            $args->{error} = 'TOO_MANY_THREADS';
            return 0;
        }
    }

    push @data, join( "\t", $my_group, $args->{stamp}, $ip_addr );
    $iRepos->set_binary( "I:F:T.${bbs}", join( "\n", @data ) );
    $iRepos->save();

    return 1;
}

1;
__END__
